Sunday 9 March 2014

invokeAll: Batch Execution

invokeAll provides a way to submit all the callable tasks to the Thread Pool at a time.

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException
Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list.

import java.util.concurrent.*;
import java.util.*;

public class CallableTask<String> implements Callable<String>{
 String name;

 CallableTask(String name){
  this.name = name;
 }

 public String call(){
  try{
   Thread.sleep(1000);
   System.out.println(name +" Finishes Execution");
  }
  catch(Exception e){
   System.out.println("Task Interrupted " + e);
  }
  return (String)(new Date() + " :: " + name);
 }
}

import java.util.concurrent.*;
import java.util.*;

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  List<CallableTask<String>> l1 = new ArrayList<> ();
  List<Future<String>> f1;

  /* Create 5 Callable Tasks */
  CallableTask<String> task1 = new CallableTask<> ("Task1");
  CallableTask<String> task2 = new CallableTask<> ("Task2");
  CallableTask<String> task3 = new CallableTask<> ("Task3");
  CallableTask<String> task4 = new CallableTask<> ("Task4");
  CallableTask<String> task5 = new CallableTask<> ("Task5");

  /* Adding the tasks to the list of type Callable */
  l1.add(task1);
  l1.add(task2);
  l1.add(task3);
  l1.add(task4);
  l1.add(task5);

  /*Submitting all the tasks in the list l1 to the Thread pool */
  f1 = exec.invokeAll(l1);
  exec.shutdown();
  exec.awaitTermination(3, TimeUnit.SECONDS);

  /* Priniting the resultes returned by the tasks */
  for(Future obj : f1)
   System.out.println(obj.get());
 }
}

Output
Task2 Finishes Execution
Task1 Finishes Execution
Task3 Finishes Execution
Task5 Finishes Execution
Task4 Finishes Execution
Sun Mar 09 13:35:20 IST 2014 :: Task1
Sun Mar 09 13:35:20 IST 2014 :: Task2
Sun Mar 09 13:35:20 IST 2014 :: Task3
Sun Mar 09 13:35:21 IST 2014 :: Task4
Sun Mar 09 13:35:21 IST 2014 :: Task5
   
ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
Above statement create a thread pool of size 3. So it can run 3 tasks at a time, Since 3 threads are reside in the pool.

exec.submit(task1, "Task1 Execution Finished");
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the run method of the Runnable Object. Once the task is finished the result 'Task1 Execution Finished' is returned to the Future Object.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment