Sunday, July 7, 2013

Concurrency in java. ExecutorService.

High-level API for concurrency support appeared in Java 5. It includes different tools that make easier life for developers who work with a multi-threaded environment.

In particular, java.util.concurrent package contains a number of classes that help quick organize a thread pool. The following class diagram illustrates their hierarchy:


Inheritance hierarchy of classes for thread pool organizing


As you can see from class diagram, there are 3 classes for thread pooling:

ThreadPoolExecutor (since 1.5) – helps to create thread pool and organize execution of list of asynchronous tasks. See example here.

ScheduledThreadPoolExecutor(since 1.5) – in addition to capabilities of ThreadPoolExecutor, helps to schedule, delay task execution or set periodicity. See examples here.

ForkJoinPool(since 1.7) – the main part of Fork/Join framework in Java.

And each of these classes implements ExecutorService interface. Let’s see on their general interface:

ExecutorService methods


This is a brief overview of ExecutorService methods:

shutdown() – activates shutdown process. By default, using factory methods of Executors class or constructors of corresponding classes, non-daemon threads are created that prevents JVM from shutting down unless you shutdown thread pool explicitly. After shutdown call new tasks cannot be submitted for execution and, most importantly, it doesn’t wait for finishing of already submitted tasks. Therefore this method is better to use together with awaitTermination (of course if it is important for you that previously submitted tasks need to be finished).

shutdownNow() – also activates shutdown process, but here method try to interrupt running tasks and return List of tasks that were submitted but which execution has not yet started. And again if you need that running tasks to be finished use awaitTermination (note the difference: here we talk about running tasks and in the previous method about submitted tasks).

isShutdown() – will be true if it was called shutdown or shutdownNow methods

isTerminated() – will be true if all tasks have completed after call of shutdown or shutdownNow.

awaitTermination(long, TimeUnit) – waits until all tasks (submitted or running, see shutdown, shutdownNow) have completed.

submit – all three methods submit task for execution and return Future as a result. The difference between submit(Callable<T>) and submit(Runnable, T) is in some distinction between interfaces Callable and Runnable. And the last submit(Runnable task) method returns Future which get method returns null if execution was successful.

invokeAll – the first method: executes tasks and returns their Future when tasks are completed. The second one – when tasks are completed or timeout expires.

invokeAny methods execute tasks and return the result of only one task that was completed successfully, the others tasks are canceled.

No comments:

Post a Comment