为什么 ExecutorService.invokeAll() 返回一个未来列表?

use*_*663 4 java concurrency

invokeAll()直到Callable提交中的所有sCollection都完成后才返回,那么结果Futures的原因是什么?

Sle*_*idi 6

Because the task might terminate normally or exceptionally, Futures can wrap the exception for you. For example,

Callable<Integer> c1 = () -> 1;
Callable<Integer> c2 = () -> {
        throw new RuntimeException();
};

List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(c1,c2));
for (Future<Integer> future : futures) {
  System.out.println(future.get());
}
Run Code Online (Sandbox Code Playgroud)

Note that because of Future, we were able to get a result of the future that terminated normally and the that terminated exceptionally.

If invokeAll returned a List<T>, it would have to return those that completed successfully and discarded those with exceptions.