0

I am using java.util.concurrent package to create a parallel program. I have 2 threads:

  • thread-1 which invokes webservice method-1, and
  • thread-2 which invokes webservice method-2.

I am specifying a thread execution timeout - suppose if thread-1 does not complete execution within the specified timeout then I have to intercept thread-1, continue the execution with thread-2 and display thread-2 results in jsp (note: if both threads take too much time to process the requests then I don't want the UI to wait until they complete).

I tried with the code below but it throws an InterruptedException. How can I proceed with other tasks when one task takes more mire?

ExecutorService executor = Executors.newFixedThreadPool(2);
CompletionService<ArrayList<AvailableWeatherDetailVO>> compService =   new ExecutorCompletionService<ArrayList<AvailableWeatherDetailVO>>(executor);
// Start amazonTask using thread-1
try{
   compService.submit(amazonTask).get(20, TimeUnit.MILLISECONDS);
   amazonFuture = compService.take();
  amazonFinalList =(ArrayList<AvailableWeatherDetailVO>)amazonFuture .get()                 }
catch (TimeoutException e) {
  compService.submit(amazonTask).cancel(true);
  //throw new TimeoutException("Thread not executed with in speifed time");
 }
// Start googleTask using thread-2
try{
   compService.submit(googleTask).get(100, TimeUnit.MILLISECONDS);
   googleFuture = compService.take();
  googleFinalList =(ArrayList<AvailableWeatherDetailVO>)googleFuture .get()                 }
catch (TimeoutException e) {
  compService.submit(googleTask).cancel(true);
  //throw new TimeoutException("Thread not executed with in speifed time");
 }
assylias
  • 321,522
  • 82
  • 660
  • 783
rev
  • 77
  • 1
  • 8

1 Answers1

0

It is not clear if you mean thread2 only begins execution if thread1 fails.

Or, are they both executing, but you want to use the result of thread1 if it completes, else you want to use the result of thread2

It sounds to me like you should attach thread 1 to a Future. Then get the result (from your main thread) with a timeout. If the Future.get() times out, then get the result from the second thread.

Not sure if I got your meaning. If this is not what you are looking for, please clarify.

Victor Grazi
  • 15,563
  • 14
  • 61
  • 94