首页 > 解决方案 > ExecutorService 使用 Stream 时不并行执行线程

问题描述

我正在使用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()一次只执行一个。

到底是怎么回事?

标签: multithreadingjava-8

解决方案


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

问题出在这种模式中:

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

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

使固定:

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

这会强制所有线程被提交。


推荐阅读