使用带有并行流的forEachOrdered的好处 [英] Benefit of using forEachOrdered with Parallel streams

查看:554
本文介绍了使用带有并行流的forEachOrdered的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

官方Oracle文档说:

The official Oracle documentation says:


请注意,如果使用forEachOrdered等
操作,可能会失去并行性的好处使用并行流。
Oracle - Parallelism

如果我们失去并行性,为什么有人会使用并行流使用 forEachOrdered

Why would anyone use forEachOrdered with parallel stream if we are losing parallelism?

推荐答案

取决于情况,通过使用并不会失去所有并行性的好处 ForEachOrdered

depending on the situation, one does not lose all the benefits of parallelism by using ForEachOrdered.

假设我们有这样的东西:

Assume that we have something as such:

stringList.parallelStream().map(String::toUpperCase)
                           .forEachOrdered(System.out::println);

在这种情况下,我们可以保证 ForEachOrdered 终端操作会在遭遇顺序中打印出大写的字符串,但是我们不应该假设这些元素将被传递给 map 中间件按照他们选择进行处理的相同顺序操作。 map 操作将由多个线程同时执行。因此,人们仍然可以从并行性中受益,但这只是因为我们没有充分发挥并行性的潜力。总而言之,我们应该使用 ForEachOrdered ,这对于按照流的遭遇顺序执行操作很重要。

In this case, we can guarantee that the ForEachOrdered terminal operation will print out the strings in uppercase in the encounter order but we should not assume that the elements will be passed to the map intermediate operation in the same order they were picked for processing. The map operation will be executed by multiple threads concurrently. So one may still benefit from parallelism but it's just that we’re not leveraging the full potential of parallelism. To conclude, we should use ForEachOrdered when it matters to perform an action in the encounter order of the stream.

编辑以下评论:


跳过<$ c $时会发生什么c>地图操作?我对 parallelStream()

如果您指的是以下内容:

if you're referring to something as in:

 stringList.parallelStream().forEachOrdered(action);

做这样的事情没有任何好处我怀疑这是什么设计师在决定创建方法时考虑到了这一点。在这种情况下,做更有意义:

there is no benefit in doing such thing and I doubt that's what the designers had in mind when they decided to create the method. in such case, it would make more sense to do:

stringList.stream().forEach(action);

扩展你的问题如果我们失败,为什么有人会使用带有并行流的forEachOrdered并行,假设你想对每个元素执行一个关于流遇到顺序的动作;在这种情况下你将需要使用 forEachOrdered ,因为 forEach 终端操作是非确定性并行使用时,顺序流有一个版本,并行流有一个

to extend on your question "Why would anyone use forEachOrdered with parallel stream if we are losing parallelism", say you wanted to perform an action on each element with respect to the streams encounter order; in such case you will need to use forEachOrdered as the forEach terminal operation is non deterministic when used in parallel hence there is one version for sequential streams and one specifically for parallel streams.

这篇关于使用带有并行流的forEachOrdered的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆