java - Java Parallel Stream 与 ExecutorService 的性能
问题描述
假设我们有一个列表并且想要选择所有满足某个属性的元素(比如说一些函数 f)。有 3 种方法可以并行此过程。
一 :
listA.parallelStream.filter(element -> f(element)).collect(Collectors.toList());
二:
listA.parallelStream.collect(Collectors.partitioningBy(element -> f(element))).get(true);
三:
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
//separate the listA into several batches
for each batch {
Future<List<T>> result = executorService.submit(() -> {
// test the elements in this batch and return the validate element list
});
}
//merge the results from different threads.
假设测试功能是一个 CPU 密集型任务。我想知道哪种方法更有效。非常感谢。
解决方案
一号和二号使用 ForkJoinPool,专为并行处理一个任务而设计,而 ThreadPoolExecutor 用于并发处理独立任务。所以一号和二号应该更快。
推荐阅读
- python - Pandas - 如何用范围时间条件填充列
- spring-batch - 在 SpringBatch 中使用 ClassifierCompositeItemProcessor 时,通过 StepBuilderFactory stream() 将文件名动态传递给 FlatFileItemWriter
- awk - 如何使用awk或正则表达式过滤日志
- ios - SwiftUI TabView 在显示包含在所述选项卡不可见时更改的数据的选项卡时崩溃
- c# - 使用嵌套对象 c# 的 Dapper 多重映射
- python - Python-当我将一个列表中的项目移动到另一个列表时,有些项目丢失了
- php - Php facebook webdriver (selenium) 在 ubuntu 18.04 上不起作用
- visual-studio-code - vs代码中特定变量的自定义着色
- audiokit - 模块“AudioKit”没有名为“inputDevices”的成员
- kubernetes - PVC 事件:等待由外部配置程序“csi.vsphere.vmware.com”创建或由系统管理员手动创建的卷