Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out-of-order returns from Java Futures

The only model that I can come up with for running multiple similar processes (SIMD) using Java Futures (java.util.concurrent.Future<T>) is as follows:

class Job extends Callable<T> {
  public T call() {
    // ...
  }
}
List<Job> jobs = // ...
List<Future<T>> futures = ExecutorService.invokeAll(jobs);
for (Future<T> future : futures) {
  T t = future.get();
  // Do something with t ...
}

The problem with this model is that if job 0 takes a long time to complete, but jobs 1, 2, and 3 have already completed, the for loop will wait to get the return value from job 0.

Is there any model that allows me to get each Future result as it becomes available without just calling Future.isDone() and busy waiting (or calling Thread.sleep()) if none are ready yet?

like image 468
Ralph Avatar asked May 04 '11 10:05

Ralph


People also ask

Does Future get block Java?

A Future interface provides methods to check if the computation is complete, to wait for its completion and to retrieve the results of the computation. The result is retrieved using Future's get() method when the computation has completed, and it blocks until it is completed.

How do futures work in Java?

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

What is a Future How is it used in ExecutorService?

It represents the result of a computation that will be completed at a later point of time in future. ExecutorService. submit() method returns immediately and gives you a Future. Once you have obtained a future, you can execute other tasks in parallel while your submitted task is executing, and then use future.

What is Future multithreading?

Think of a Future as an object that holds the result – it may not hold it right now, but it will do so in the future (once the Callable returns). Thus, a Future is basically one way the main thread can keep track of the progress and result from other threads.


1 Answers

You can try out the ExecutorCompletionService:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html

You would simply submit your tasks and call take until you've received all Futures.

like image 56
Thomas Jungblut Avatar answered Nov 15 '22 17:11

Thomas Jungblut