执行器服务在使用流<Future>时未并行执行线程



我正在使用如下ExecutionService

ExecutorService exe = Executors.newWorkStealingPool(parts.size());
...
Stream<Future<String>> futures = parts.stream().map(part -> exe.submit(() -> processPartition(part)));
...
String ret[] = futures.map(t -> {
try {
return t.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}).toArray(n -> new String[n]);

processPartition()中的代码一次只执行一个。

这是怎么回事?

我花了几个小时对此进行故障排除,然后在发布后 2 分钟终于找到了答案。

问题出在此模式中:

Stream<Future<String>> futures = [...]

通过使用流,在调用每个相应的map(t ->之前,不会提交每个 Future 。

修复:

List<Future<String>> futures = [...] .collect(Collectors.toList());

这会强制提交所有线程。

最新更新