如何在不关机的情况下等到ExecutorService中所有提交的任务完成?

How to wait until all submitted tasks in ExecutorService are completed without shutdown?

假设我们遍历一个集合并在后台提交任务运行

class Processor {
    public void process(Iterable<Item> items, ExecutorService executorService) {
       for (Item item : items) {               
           doStandardProcess(item);               
           if (needSpecialProcess(item)) {
               executorService.submit(createSpecialTaskFor(item));
           }
       }
    }
}

程序流程如下:

  1. 从某处接收物品
  2. 创建处理器并处理它们
  3. 将结果发送到某个地方

结果取决于后台处理,所以p.3应该等到所有任务完成。我知道可以通过 shutdown()awaitTermination() 的组合来实现,但我不想关闭该服务。也有可能调用 invokeAll(List tasks),但如您所见,任务是在遍历期间一个接一个地创建的。

如何在给定的限制条件下实现等待完成?

P.S。如果不清楚,另一个限制是 运行 后台任务与项目遍历并行,因为后台任务比基本处理操作多花费 x100 倍的时间。

List<Callable<Foo>> toProcess = new ArrayList<>();
for (Item item : items) {
    if (needProcess(item)) {
        toProcess.add(createTaskFor(item));
    }
}
executorService.invokeAll(toProcess);

您可以存储期货:

List<Future> futures = new ArrayList<> ();
//in the for loop
futures.add(executorService.submit(createTaskFor(item)));

//after for loop + add exception handling
for (Future f : futures) f.get();
//at this point all tasks have finished