Java ExecutorService is an interface that extends
Executor class and represents an asynchronous execution. It provides us mechanisms to manage the end and detect progress of the asynchronous tasks.
In this example, we are going to see some basic functionalities of
ExecutorService, as well as handle the
Future object, the result of asynchronous computation.
1. Runnable vs Callable
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. However Runnable interface cannot do everything that Callable does:
- Callable instance returns a result, whereas a Runnable instance does not.
- Callable instance may throw checked exceptions, whereas as Runnable instance can not.
2. Create the Runnable
We are going to create a
Runnable that is intended to be executed by the
ExecutorService. Create a java class named
myThread and paste the following code.
The functionality of the
Runnable is very simple. It computes a sum from the giving argument and it sleeps for a specified time.
3. Code the ExecutorService in Java
In this example we will use a factor method of
ExecutorService that creates a thread pool of fixed number of threads. For this reason,
newFixedThreadPool() method is used where we specify the number of threads in the pool. To execute the thread, we can use either
execute() method or
submit(), where both of them take
Runnable as a parameter.
execute() method is depending on the implementation of the
Executor class and may perform the
Runnable in a new thread, in a pooled thread, or in the calling thread.
submit() method extends
execute(), by returning a
Future that represents the submitting task.
Future can be used to indicate the termination of execution of the thread. For instance,
get() method waits for the completion of the computation. If the returning value is null, the task has finished correctly. Otherwise,
cancel() method can be called in order to end the execution of this task. It is worth to mention that for bulk or a collection of thread execution,
invokeAny() are used respectively, although there are not used in this example.
To close down the
ExecutorService, there are many methods that can be used. In our example we use
shutdown() method, in which the submitted tasks are executed before the shutting down but new tasks can not be accepted. Another approach is
shutdownNow() method, which stops the executing tasks, pause the waiting ones and returns the list of the awaiting ones. Moreover,
awaitTermination() can be used in order to wait until all threads are terminated.
For further understanding of the main functionality of
ExecutorService, have a look at the code below. Create
ExecutorServiceTest.java file and paste the following.
Now you can see the output of the execution.
TaskOne thread has sum = 3 and is going to sleep for 100 TaskTwo thread has sum = 10 and is going to sleep for 200 TaskThree thread has sum = 15 and is going to sleep for 100 1) TaskTwo terminated successfully 1) TaskThree terminated successfully TaskTwo thread has sum = 10 and is going to sleep for 200 TaskThree thread has sum = 15 and is going to sleep for 100 2) TaskTwo terminated successfully 2) TaskThree terminated successfully ----------------------- All tasks are finished!
4. The ScheduledExecutorService Interface
java.util.concurrent.ExecutorService thus it inherits all the functional abstractions from ExecutorService interface (and its super interfaces!); nevertheless, the difference being,
ScheduledExecutorService can “schedule commands to run after a given delay, or to execute periodically” (Source).
The public API to use
ScheduledExecutorService is pretty straightforward. We can “schedule” a repetitive or delayed task encapsulated in a
java.util.concurrent.Callable instance with
ScheduledExecutorService configuring the delays. It is obvious that a Runnable task would be non result bearing one and Callable would produce some result.
An instance of
ScheduledThreadPoolExecutor can be retrieved from the convenient factory API,
java.util.concurrent.Executors.newScheduledThreadPool(int corePoolSize) or its overloaded version
Executors.newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory). In the subsequent sections, we will demonstrate these APIs through the way of an example.
5. ExecutorService vs Fork/Join Pool
Each of these APIs are targeted to fulfil respective business needs of your application.
ExecutorService is an interface that extends Executor class and represents an asynchronous execution. It provides us mechanisms to manage the end and detect progress of the asynchronous tasks.
- Executor service manage thread in asynchronous way
- Use callable to get the return result after thread completion
- Manage allocation of work to free thread and resale completed work from thread for assigning new work automatically
- Better communication between threads
- invokeAll and invokeAny give more control to run any or all thread at once
- shutdown provide capability for completion of all thread assigned work
- Scheduled Executor Services provide methods for producing repeating invocations of runnables and callables Hope it will help you
Fork-Join framework is an extension to Executor framework to particularly address ‘waiting’ issues in recursive multi-threaded programs. In fact, the new Fork-Join framework classes all extend from the existing classes of the Executor framework. ForkJoinPool is for many, dependent, task-generated, short, hardly ever blocking (i.e. compute-intensive) tasks
- parallelism – the parallelism level. For default value, use Runtime.availableProcessors()
- factory – the factory for creating new threads. For default value, use defaultForkJoinWorkerThreadFactory
- handler – the handler for internal worker threads that terminate due to unrecoverable errors
- asyncMode – if true, establishes local first-in-first-out scheduling mode for forked tasks that are never joined.
6. Download the source code
This was an example of ExecutorService in Java.
Download the source code of this example: Java ExecutorService Example – Tutorial
Last updated on May 25th, 2020