Java 流 API : why the distinction between sequential and parallel execution mode?

标签 java parallel-processing java-8 java-stream

来自Stream javadoc :

Stream pipelines may execute either sequentially or in parallel. This execution mode is a property of the stream. Streams are created with an initial choice of sequential or parallel execution.

我的假设:

  1. 顺序流/并行流之间没有功能差异。输出永远不会受到执行模式的影响。
  2. 并行流总是更可取,考虑到适当数量的内核和问题大小以证明开销合理,因为性能提升。
  3. 我们希望一次编写代码并在任何地方运行,而不必关心硬件(毕竟这是 Java)。

假设这些假设是有效的(有点元假设没有错),在 API 中公开执行模式有什么值(value)?

看起来你应该能够声明一个Stream,并且顺序/并行执行的选择应该在下面的层中自动处理,要么通过库代码,要么通过 JVM 本身作为运行时可用内核的功能、问题的大小等。

当然,假设并行流也可以在单核机器上工作,也许只是始终使用并行流就可以实现这一点。但这真的很难看 - 为什么在默认选项下在我的代码中显式引用并行流?

即使在某种情况下,您会故意对顺序流的使用进行硬编码——为什么不只是为此目的使用一个子接口(interface) SequentialStream,而不是污染 Stream 带有执行模式开关?

最佳答案

It seems like you should just be able to declare a Stream, and the choice of sequential/parallel execution should be handled automagically in a layer below, either by library code or the JVM itself as a function of the cores available at runtime, the size of the problem, etc.

现实是 a) 流是一个库,没有特殊的 JVM 魔力,并且 b) 你无法真正设计一个足够聪明的库来自动找出在这种特殊情况下正确的决定是什么。没有明智的方法来估计一个特定函数在不运行它的情况下会有多昂贵——即使你可以反省它的实现,但你不能——现在你正在为每个流操作引入一个基准,试图找出如果并行化,那么并行化开销的成本是值得的。这只是不切实际,尤其是考虑到您事先也不知道并行性开销有多糟糕。

A parallel stream is always preferable, given appropriate number of cores and problem size to justify the overhead, due to the performance gains.

在实践中并非总是如此。有些任务太小了,不值得并行化,并行化总是有一些开销。 (坦率地说,大多数程序员往往高估了并行性的用处,当它确实损害性能时到处乱用它。)

基本上,这是一个足够困难的问题,您基本上必须将其推给程序员。

关于Java 流 API : why the distinction between sequential and parallel execution mode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22950642/

相关文章:

c# - 如何使用 C# 和并行扩展并行化顺序任务?

java - 使用流在列表列表中查找对象

java - "Don' t show anymore"ThickBox in Android Activity

java - 名称冲突 : The method add(Object) of type test2 has the same erasure as add(E) of type HashSet<E> but does not override it

c# - 具有 "per-object"方法的语言的示例是什么?

perl - 我应该如何在 Perl 中实现原子序列?

algorithm - 集合交集的并行算法

Java 8 Stream API toMap 转换为 TreeMap

java - 根据流中的另一个字段汇总字段

java - 动态规划-记忆化