温馨提示:本文翻译自stackoverflow.com,查看原文请点击:java - Should I always use a parallel stream when possible?
java parallel-processing java-8 java-stream

java - 如果可能,是否应该始终使用并行流?

发布于 2020-03-27 11:07:25

使用Java 8和lambda,可以很容易地将集合作为流进行迭代,也很容易使用并行流。docs中的两个示例,第二个示例使用parallelStream:

myShapesCollection.stream()
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));

myShapesCollection.parallelStream() // <-- This one uses parallel
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));

只要我不关心顺序,使用并行会一直有益吗?有人会认为,更快地将工作划分到更多的内核上。

还有其他考虑事项吗?什么时候应该使用并行流,什么时候应该使用非并行?

(问这个问题引发了关于如何以及何时使用并行流的讨论,不是因为我认为始终使用并行流是一个好主意。)

查看更多

查看更多

提问者
Matsemann
被浏览
95
7,968 2017-05-10 11:07

A parallel stream has a much higher overhead compared to a sequential one. Coordinating the threads takes a significant amount of time. I would use sequential streams by default and only consider parallel ones if

  • I have a massive amount of items to process (or the processing of each item takes time and is parallelizable)

  • I have a performance problem in the first place

  • I don't already run the process in a multi-thread environment (for example: in a web container, if I already have many requests to process in parallel, adding an additional layer of parallelism inside each request could have more negative than positive effects)

在您的示例中,无论如何,性能都将受到对的同步访问的驱动System.out.println(),并且使此过程并行不会产生影响,甚至不会产生负面影响。

此外,请记住,并行流并不能神奇地解决所有同步问题。如果过程中使用的谓词和函数使用了共享资源,则必须确保所有内容都是线程安全的。尤其是副作用,如果并行使用,您确实要担心。

无论如何,不​​要猜测!只有度量会告诉您并行性是否值得。