arinte
arinte

Reputation: 3728

Why would invokeAll() not return?

I have roughly this code:

ExecutorService threader = Executors.newFixedThreadPool(queue.size());
List futures = threader.invokeAll(queue);

I debug this and invokeAll doesn't seem to return until all the threads in the Queue are finished. Any reasons why this is happening.

Upvotes: 4

Views: 3793

Answers (3)

Vikash
Vikash

Reputation: 41

When we call invokeAll() method it returns List<Futute<T>> object. And this Future object holds the value of all threads untill it is successfully executed. So when we try to try to iterate through Future<T> object it first internally checks Future<T>.isDone() [We may or may not check Future<T>.isDone() externally]. If it returns true we can iterate through the object and can access the value of the Future<T> Object, else it waits until true.

Note: If Future<T> gets a false object it will not allow you to iterate through the object.

ExecutorService threader = Executors.newFixedThreadPool(queue.size());  
List<Future<T>> listFuture = threader.invokeAll(queue);  
for(Future<T> future: listFuture) {
    // Here you have the full access to this future object  
}

Upvotes: 2

Pete Kirkham
Pete Kirkham

Reputation: 49321

Executes the given tasks, returning a list of Futures holding their status and results when all complete. the API

You have to submit() them one at a time instead, something like:

public static <T> List<Future<T>> submitAll ( ExecutorService executor, Collection<? extends Callable<T> > tasks ) {
    List<Future<T>> result = new ArrayList<Future<T>>( tasks.size() );

    for ( Callable<T> task : tasks )
        result.add ( executor.submit ( task ) );

    return result;
}

Upvotes: 8

Johannes Weiss
Johannes Weiss

Reputation: 54081

Because it's designed like that:

[...]
Executes the given tasks, returning a list of Futures holding their status and results when all complete. 
[...]

is a quote from http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection)

Upvotes: 6

Related Questions