Joshua Bloch 在 <Effective Java> (Third Edition)
提到
The operations performed by Stream’s collect method, which are known as mutable reductions, are not good candidates for parallelism because the overhead of combining collections is costly.
我阅读了 Mutable reduction 上的文档,但我仍然不太确定为什么缩减不是并行的好选择。是synchronization
吗?
正如@Ravindra Ranwala 所指出的(我也在 Reduction, concurrency, and ordering 文档中看到了这一点):
It may actually be counterproductive to perform the operation in parallel. This is because the combining step (merging one Map into another by key) can be expensive for some Map implementations.
如果是这样,那么是否还有其他我们需要关注的主要因素可能会导致性能低下?
最佳答案
不,这与同步
无关。假设您有 100 万个 Person
对象,并且需要找出住在纽约的所有 people
。所以一个典型的流管道是,
people.parallelStream()
.filter(p -> p.getState().equals("NY"))
.collect(Collectors.toList());
考虑并行执行此查询。假设我们有 10 个线程并行执行它。每个线程都会将自己的数据集累积到一个单独的本地容器中。最后将 10 个结果容器合并为一个大容器。此合并 的成本很高,并且是并行执行引入的附加步骤。因此并行执行可能并不总是更快。有时顺序执行可能比并行计数器部分更快。
所以总是从顺序执行开始。如果这有意义,您可能会在稍后的某个时间点回退到它的并行对应物。
关于java - Java 8 中 parallelStream 的变异减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50869179/