Usage of Executor service
Posted By : Abhishek Saini | 20-Sep-2018
The ExecutorService is an interface and is used to represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is very similar to a thread pool. We can also say that the implementation of ExecutorService present in the java.util. The concurrent package is a thread pool implementation.
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
executorService.shutdown();
When you instantiate Executor Service, a few parameters are initialized. Its totally depends on how you instantiated your Executor Service in your application program, you also can manually specify these parameters, or they may be provided by default. These parameters are:
1.
2.
3. workQueue
4. keepAliveTime
5. threadFactory
6.rejectedExecutionHandler
ackage com.journaldev.threadpool;
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for(int j = 0; j < 10; j++) {
Runnable worker = new WorkerThread("" + j);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
In above example, we are defining fixed size thread pool of 5 threads. Then we are submitting 10 jobs to this pool, but since the pool size is 5, it will first start working on 5 jobs and other jobs going to be in wait state, as soon as any one of the job is finished, another job from the wait queue will be picked up by worker thread and get executed.
Hope this will help.
Thanks.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Abhishek Saini
Abhishek is bright Lead developer with skills in AngularJS and Java. He loves to learn new technologies.