Sunday, 9 March 2014

Batch Execution with time out and get result of one task

<T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.

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,2, TimeUnit.SECONDS);
  System.out.println(result);

  /* Priniting the resultes returned by the tasks */
  exec.shutdown();
 }
}

Sample Output
Sun Mar 09 21:00:59 IST 2014 :: Task3



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment