Java Parallel Stream 与 ExecutorService 的性能

Pol*_*ris 5 java parallel-processing java-stream java-threads

假设我们有一个列表并且想要选择满足某个属性的所有元素(比如一些函数 f)。有 3 种方法可以并行执行此过程。

一 :

listA.parallelStream.filter(element -> f(element)).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

二:

listA.parallelStream.collect(Collectors.partitioningBy(element -> f(element))).get(true);
Run Code Online (Sandbox Code Playgroud)

三:

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.
Run Code Online (Sandbox Code Playgroud)

假设测试功能是 CPU 密集型任务。我想知道哪种方法更有效。非常感谢。

Evg*_*eev 5

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