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.  corePool size
2. 
maxPool size
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.

About Author

Author Image
Abhishek Saini

Abhishek is bright Lead developer with skills in AngularJS and Java. He loves to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..