📜 ⬆️ ⬇️

Java multithreading: ExecutorService

In Java 5, many things were added for multithreading, and especially with regard to the organization of parallel access. In this and subsequent articles we will go through some of them.

ExecutorService


Before Java 5, in order to organize work with several threads, you had to use third-party pooling implementations or write your own. With the advent of ExecutorService such a need has disappeared.

ExecutorService executes asynchronous code in one or more threads. Creating an ExecutorService instance is done either manually through specific implementations ( ScheduledThreadPoolExecutor or ThreadPoolExecutor ), but it will be easier to use the Executors class factory. For example, if you need to create a pool with 2 threads, this is done like this:
ExecutorService service = Executors.newFixedThreadPool(2);

If you want to use a caching thread pool, which creates threads as needed, but re-uses inactive threads (and cleans up threads that have been inactive for a while), then this is defined as follows:
ExecutorService service = Executors.newCachedThreadPool();

Now a small example. Suppose you need to run some code asynchronously 10 times. Based on the above, the code will look like this:
ExecutorService service = Executors.newCachedThreadPool();
for ( int i = 0; i < 10; i++) {
service.submit( new Runnable() {
public void run() {
// snip... piece of code
}
});
}


The submit method also returns a Future object that contains information about the execution status of the passed Runnable or Callable (which can return a value). From it, you can find out whether the transferred code has completed successfully, or whether it is still being executed. Calling the get method on the Future object will return a value that returns Callable (or null if Runnable used). The method has 2 checked-exceptions: InterruptedException , which is thrown when execution is interrupted via the interrupt() method, or ExecutionException if the code in Runnable or Callable threw a RuntimeException , which solves the problem of supporting exceptions between threads.

ScheduledExecutorService


Sometimes it is required to execute code periodically and periodically, or it is necessary to execute the code after some time, then the ScheduledExecutorService comes to the rescue. It allows you to put the code to run in one or more threads and configure the interval or time for which the execution will be delayed. The interval can be the time between two consecutive starts or the time between the end of one execution and the beginning of another. The ScheduledExecutorService methods return a ScheduledFuture , which also contains the deferral value for running the ScheduledFuture .
')
For example, if you want to delay execution for 5 seconds, you will need the following code:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule( new Runnable() { ... }, 5, TimeUnit.SECONDS);


If you want to assign execution every second:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate( new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);


And finally, if you want to assign code execution with an interval of 1 second between executions:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay( new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);

Source: https://habr.com/ru/post/116363/


All Articles