Java ExecutorServiceThe Java ExecutorService is the interface which allows us to execute tasks on threads asynchronously. The Java ExecutorService interface is present in the java.util.concurrent package. The ExecutorService helps in maintaining a pool of threads and assigns them tasks. It also provides the facility to queue up tasks until there is a free thread available if the number of tasks is more than the threads available. Methods of Java ExecutorService
A simple program of Java ExecutorServiceOutput: In this program, we are creating an ExecutorService with ten threads and assigning it an anonymous runnable implementation which performs a task to print "ExecutorService" and after its task is over, we are shutting down the executor service. How to use Java ExecutorServiceInstantiating ExecutorServiceWe can use Java ExecutorService to create a single thread, a pool of threads, or a scheduled pool of threads. The Executors class provides factory methods to instantiate an ExecutorService as follows- Assigning tasks to ExecutorServicesTo assign a task to ExecutorService, we can use the following methods-
Example of assigning a task to ExecutorService using execute() method The Java ExecutorService's execute() method takes in a runnable object and performs its task asynchronously. After making the call to execute method, we call the shutdown method, which blocks any other task to queue up in the executorService. Output: ExecutorService Example of assigning a task to ExecutorService using submit() The submit() method takes in a runnable object and returns a Future object. This object is later on used to check the status of Runnable whether it has completed execution or not. Example of assigning a task to ExecutorService using invokeAny() method The invokeAny() method takes a collection of Callablle objects or objects of classes implementing Callable. This method returns the future object of the callable object which gets successfully executed first. Output: result = Task 1 The result stores Task 1 as the first callable object is successfully executed first. Example of assigning a task to ExecutorService using invokeAll() method The invokeAll() method takes in a Collection of Callable objects having tasks and returns a list of Future objects containing the result of all the tasks. Output: future.get = Task 1 future.get = Task 3 future.get = Task 2 How to shut down ExecutorServiceOnce we are done with our tasks given to ExecutorService, then we have to shut it down because ExecutorService performs the task on different threads. If we don't shut down the ExecutorService, the threads will keep running, and the JVM won?t shut down. The process of shutting down can be done by the following three methods-
Next TopicJava Tutorial
|