nano7
nano7

Reputation: 2493

Java: ExecutorService with Callables: invokeAll() and future.get() - results in correct order?

Im using the ExecutorService in Java to invoke Threads with invokeAll(). After, I get the result set with future.get(). Its really important that I receive the results in the same order I created the threads.

Here is a snippet:

try {
    final List threads = new ArrayList();

    // create threads
    for (String name : collection)
    {
        final CallObject object = new CallObject(name);
        threads.add(object);
    }

    // start all Threads
    results = pool.invokeAll(threads, 3, TimeUnit.SECONDS);

    for (Future<String> future : results)
    {
        try
        {
            // this method blocks until it receives the result, unless there is a 
            // timeout set.
            final String rs = future.get();

            if (future.isDone())
            {
                // if future.isDone() = true, a timeout did not occur. 
               // do something
            }
            else
            {
                // timeout
                // log it and do something
                break;
            }
        }
        catch (Exception e)
        {
        }
    }

}
catch (InterruptedException ex)
{
}

Is it assured that I receive the results from future.get() in the same order I created new CallObjects and added them to my ArrayList? I know, Documentation says the following: invokeAll(): returns a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list. If the operation did not time out, each task will have completed. If it did time out, some of these tasks will not have completed. But I wanted to make sure I understood it correctly....

Thanks for answers! :-)

Upvotes: 3

Views: 6505

Answers (2)

Siva Kumar
Siva Kumar

Reputation: 2006

As per the documentation you will get the futures in same order.

Future object is just a reference of the task.

Future#get() is blocking call.

For ex

We have submitted 4 tasks.

Task 1 - > Completed

Task 2 --> Completed

Task 3 --> Timed Out

Task 4 --> Completed

As per our code

for (Future future : futures) {
  future.get(); }

For 1&2 second task it will return immediately. We will wait for the third task will get completed. Even 4th task completed , iteration is waiting in third task . Once third task completed or timed wait expire on that time only iteration will continue.

Upvotes: 1

Tudor
Tudor

Reputation: 62469

This is exactly what this piece of the statement is saying:

returns a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list.

You will get the Futures in the exact order in which you inserted the items in the original list of Callables.

Upvotes: 8

Related Questions