The concurrency API in Java was introduced in Java 1.5 .Java Executor framework is used to run the Runnable objects without creating new threads and reusing the existing ones as creating threads is an expensive process. It simplifies the execution of tasks in asynchronous mode.
An ExecutorService is created using Executors factory methods. The main thread delegates the task to the ExecutorService and it executes the task concurrently, independent of the thread that submitted the task.
ExecutorService is an interface and it has the following implentations:-
ExecutorService executorService1 = Executors.newSingleThreadExecutor(); ExecutorService executorService2 = Executors.newFixedThreadPool(10); ExecutorService executorService3 = Executors.newScheduledThreadPool(10);
Delegating tasks to ExecutorService
There are several ways to assign task to ExecutorService. It has methods like execute, submit ,invokeAny ,invokeAll which take a runnable or callable object.
The execute service take a runnable object and executes it asynchronously. In the above example I have created an anonymous runnable object and passed it to the execute method.
The execute() method has void return type and its doesn’t return the result of the task execution.
The submit() method take a runnable or callable object and return a Future object.The Future.get() method returns the result of the task.In case of Runnable it returns null if the task has been successfully.
The Callable result can be obtained by the Future’s object using the get method.
The invokeAll() method assigns a collection of tasks to ExecutorService and each of the task is executed.The ExecutorService returns a list of Future Objects and we can obtain the result of the all the callable objects submitted for execution.
The invokeAny() method takes a collection of Callable Objects.It returns the result of one of the Callable Object but there’s is no guarantee which of the Callable result is returned.The ExecutorService returns the result of one of the successful task (if there’s any)
To stop the threads from running in ExecutorService ,the shutdown() method is used.The ExecutorService will not shut down immediately it will no longer accept new tasks.All the tasks submitted before calling the shutdown method are executed.
There is another shutdown method called shutdownNow() which shuts down the ExecutorService immediately. This will stop all executing tasks and skip all submitted but non processing tasks. There is no guarantee given to the executing tasks.
The ExecutorService awaitTermination() method will block the thread calling it until the ExecutorService has shutdown completely or until a given time out occurs. Its usually called after shutdown() or shutdownNow() method.
References:- Oracle Docs
That’s all about ExecutorService .I hope you enjoyed reading this article.Happy Coding 🙂