Sunday 9 March 2014

InvokeAny: Batch Execution and get result of one task

<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception).

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);
  }
  catch(Exception 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<> ();
  String result;

  /* 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 */
  result = exec.invokeAny(l1);
  System.out.println(result);

  /* Priniting the resultes returned by the tasks */
  exec.shutdown();
 }
}
  
Sample Output
Sun Mar 09 20:55:48 IST 2014 :: Task2
   
   


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment