Monday, July 29

ExecutorService in java concurrency package

What is ExecutorService in java?

Executorservice is nothing but a threadpool. Threadpool is nothing but a pool of threads. Threads are nothing but Runnable or callable tasks. Runnable task is nothing but an instance of class that implements Runnable interface. Callable task is nothing but an instance of class that implements callable interface

For example :

// runnable task
public class Drive implements Runnable {
    public void run(){
    }
}

//callable task
public class Drag implements Callable{
     public string call(){
   }
}

Now If you want to run a thread How would you do that . Simple traditional way to do that is :

Public class tester{
   public static void main(string args[]){
       new Drive().start();
   }
}

Here we are executing just one thread. 

What will we do If we have to get 10 task done in parallel and for that we require to execute more than 1 thread in parallel?

For such kind of requirements threadpool is very helpful and provide very simple mechanism to execute multiple threads in parallel.

Executorservice exec=Executors.newFixedThreadPool(8);

There are multiple implementations of ExecutorService available.


  •  Single thread executor   // only one thread in the pool
  •  cached thread Pool        // cache the thread created once. terminate the thread if thread remains unused in cache for 60 seconds
  •  Fixed Thread Pool          // fixed count of thread
  • Scheduled Thread Pool  // to schedule the future task
  • Single Thread Scheduled Pool  //only one thread to schedule future task



Now if you want to submit multiple task simply what you can do is :

ExecutorService pool= Executors.newFixedThreadPool(10);
      for (int i=0;i<20;i++){
            pool.submit(new Drag().start());
       }

Once this task is done you can terminate this threadpool just by invoking shutdown() method:

pool.shutdown();

We can implment any complex logic using ExecutorSerive and the code that we need to write is very simple . Also Executor service provide in built mechanism to control the overall execution process. 

We can also use Future interface to get the return value from each thread execution and then caculate the all Future values returnd. 

In above example we could retrieve the all future results by using below code :

List<Future<String>> futures = new ArrayList<Future<String>>(10);
     for(int i = 0; i < 10; i++){
futures.add(pool.submit(new Drag()));
}
    for(Future<String> future : futures){
String result = future.get();

   //Compute the result
}

And you can imagine what complex and error prone code you would have written by using existing API (pre- 1.5 version).




No comments:

Post a Comment