ThreadPool and Executor Service in Java


Thread Pools

it is needed when you want to limit the number of thread in your application, creations of thread each time will be an performance  overhead and also require a memory for its stack.

so we have created a pool of thread, now we pass Task to be executed to the thread pool
and any idle thread from the thread pool will pick the task and executes it.

The tasks are inserted into the BlockingQueue
when new task is inserted into the queue the one thread takes lock over it dequeue it and perform the task while others thread keep waiting for the task.

Best tutorial to understand



Java 5 Provides the implementation of the thread pool in the form of Executor service

Executor Service

java.util.concurrent.ExecutorService interfaces provides the asynchronous mechanism for execution of the tasks in the background.

java.util.concurrent.*  Also contains the thread pool implementation


Executor service is used for the task delegation
A running thread delegates its task to the executor service and than can continue its own execution

There are two implementation of the executor service
1-ThreadPoolExecutor
2-ScheduledThreadPoolExecutor

3 Different ways to create an executor service depends on requirement
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
ExecutorService executorService2 = Executors.newFixedThreadPool(10);
ExecutorService executorService3 = Executors.newScheduledThreadPool(10);


ways to delegates task to executor service
1-execute(Runnable)
2-submit(Runnable)  -- returns(Future object) null on successful completion of runnable
3-submit(Callable) -- retrurn the value of call method
4-invokeAny(...)  --  takes collection of callable object and invokes any one
 not return the future object but it returns the type of object which call method returns. See Examples below
5-invokeAll(...) -- return the list of the future object  eg List<Future<String>>

task queued with execute that generated some Throwable will cause UnCaughtExceptionHandler simply prints in system.err

task queued with submit that generated some Throwable will bind it to future object which it returns future will throw an executionException


You should shutdown the executor service since active methods in the executor service prevents the JVM from shutting down.



ExecutorService executorService = Executors.newFixedThreadPool(10);
//executorService.submit()
executorService.execute(new Runnable() {
   public void run() {
       System.out.println("Asynchronous task");
   }
});




//it  will return String as output
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 1";
    }
});
String result = executorService.invokeAny(callables);
System.out.println("result = " + result);


Comments