2 Replies Latest reply: Mar 22, 2013 1:33 AM by meandmycode RSS

    Possible to connect submitted task to result when finished

    meandmycode
      Hi,

      I will send out parallell requests to differnet services to get a result ( that take different time to access).

      How can I check which task has completed and connect that to the result?

      //mike
      import java.util.concurrent.Callable;
      import java.util.concurrent.CompletionService;
      import java.util.concurrent.ExecutionException;
      import java.util.concurrent.ExecutorCompletionService;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      import java.util.concurrent.Future;
      import java.util.concurrent.TimeoutException;
      
      public class MyTasks {
           
           Callable[] tasks = new Callable[] { new StateTask(), new ProgressTask() };
           
           
           
           public static void main(String[] args) throws InterruptedException, ExecutionException,TimeoutException{
                MyTasks mt = new MyTasks();
                mt.execute();     
           }
           
           //report when all have completed...
           public void execute2()throws InterruptedException, ExecutionException,TimeoutException{
                
           }
           
           
           public void execute()throws InterruptedException, ExecutionException,TimeoutException{
                ExecutorService executor = Executors.newCachedThreadPool();
                CompletionService<String> compService = new ExecutorCompletionService<String>(
                          executor);
                
                //submit tasks
                for (Callable callable : tasks) {
                     compService.submit(callable);
                }
      
                for (int i = 0; i < tasks.length; i++) {
                     Future<String> future = compService.take();     
                     System.out.println("I get "+" " + future.get());
                     
                }
                executor.shutdown(); // always reclaim resources
                
           }
           
           // generic class to handle t
           public class StateTask implements Callable<String> {
      
                @Override
                public String call() throws Exception {
                     Thread.sleep(8000);
                     System.out.println("checking service one!");
                     return "One";
                }
      
           }
      
           class ProgressTask implements Callable<String> {
      
                @Override
                public String call() throws Exception {
                     Thread.sleep(20000);
                     System.out.println("checking service two");
                     return "Two";
                }
           }
      }