multithreading - 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()
一次只执行一个。
到底是怎么回事?
解决方案
我花了几个小时对此进行故障排除,然后在发布后 2 分钟终于找到了答案。
问题出在这种模式中:
Stream<Future<String>> futures = [...]
通过使用流,在map(t ->
调用每个对应项之前不会提交每个 Future。
使固定:
List<Future<String>> futures = [...] .collect(Collectors.toList());
这会强制所有线程被提交。
推荐阅读
- github - 如何在 Github API 中按组织 ID 查找组织存储库?
- python - Pandas 使用日期在数据框中追加周列
- android - 在android webview中为`findAllAsync`使用自定义颜色
- java - 复合键 - 休眠
- ruby-on-rails - 管袜中发生的 CORS 问题
- database - 在mongodb中将一个字段从一个集合复制到另一个集合,外键为混合类型
- javascript - 将节点名称映射到链接上
- python-3.x - PyTest:修复重复代码并删除依赖项
- asp.net - 像 Bootstrap Breadcrumb 一样自定义 SiteMapPath
- iphone - 如何为 iOS 编写沙箱以检查漏洞?