2

I'm wondering if the main thread waits until all tasks in invokeAll() parameter finish before it continues. Here's my code and it seems that it does.

public static void main(String[] args) throws InterruptedException {

    ExecutorService service = null;
    try
    {
        service = Executors.newCachedThreadPool();
        List<Callable<?>> list = new ArrayList<>();
        for(int i = 0; i < 1000; i++)
        {
            list.add(() -> {System.out.println("Not yet"); return null;});
        }
        service.invokeAll(list);
        System.out.println("END!"); // Output "END" at last no matter what
    }
    finally
    {
        if(service != null)
        {
            service.shutdown();
        }
    }
}

As you can see, no matter how many tasks I created, whether it is 1000 or 10000, the program still outputs "END" at last.

Can anyone confirms this information? Thank you so much!

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Tran Anh Minh
  • 196
  • 2
  • 12

2 Answers2

4

The ExecutorService.invokeAll() documentation states (emphasis is mine) :

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

And the ExecutorService class documentation underlines this point for every method designed to run tasks (emphasis is mine) :

Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete.

At least one being for invokeAny() and all for invokeAll().

davidxxx
  • 125,838
  • 23
  • 214
  • 215
4

This is what the javadoc for invokeAll(...) says (my commentary inserted):

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

Note: "when all complete" ... not before.

Future.isDone() is true for each element of the returned list.

This means that the tasks have completed.

Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

Parameters: tasks - the collection of tasks

Returns: A list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completed.

Once again ... it says that the tasks have completed.


In short, it says three times that the tasks have completed before invokeAll() returns.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216