首页 > 解决方案 > 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 密集型任务。我想知道哪种方法更有效。非常感谢。

标签: javaparallel-processingjava-streamjava-threads

解决方案


一号和二号使用 ForkJoinPool,专为并行处理一个任务而设计,而 ThreadPoolExecutor 用于并发处理独立任务。所以一号和二号应该更快。


推荐阅读