关于java:Stream.forEach是否遵循顺序流的遭遇顺序?

Does Stream.forEach respect the encounter order of sequential streams?

javadoc forStream.forEach表示(emphasis mine):

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.

Java 9早期访问JavaDoc中存在相同的文本。

第一句话("显式不确定性")表明(但没有显式地说)这种方法不保留遭遇顺序。但是,下一个明确表示顺序不被保留的语句是以"用于并行流管道"为条件的,如果不管并行性如何,应用该语句,则不需要这种条件。这让我不确定foreach是否保留了遇到顺序流的顺序。

这个答案指出了流库实现调用.sequential().forEach(downstream)的地方。这表明foreach旨在为顺序流保留顺序,但也可能只是库中的一个bug。

我在自己的代码中使用了安全方面的forEachOrdered避免了这种模糊性,但今天我发现netbeans ide的"use functional operations"编辑器提示将转换

1
2
for (Foo foo : collection)
    foo.bar();

进入之内

1
2
3
collection.stream().forEach((foo) -> {
    foo.bar();
});

如果foreach不保留遭遇顺序,则会引入一个bug。在我报告一个针对NetBeans的bug之前,我想知道库实际上保证了什么,由一个源进行备份。

我在找权威人士的答案。这可能是库实现中的一个明确的评论,关于Java开发邮件列表的讨论(谷歌找不到任何东西,但也许我不知道这些神奇的单词),或者来自图书馆设计者(我知道两个,Brian Goetz和斯图亚特马克)的声明是活跃的。堆栈溢出)。(请不要用"只使用foreachored代替"——我已经这样做了,但我想知道代码是否正确。)


(P)Specifications exist to describe the minimal guarantees a caller can depend on,not to describe what the implementation does.这一差距是至关重要的,因为它是执行灵活性的一部分。(specification is declarative;implementation is imperative.)overspecification is just bad as underspecification.(p)(P)当具体说明"不保全财产X"时,它并不意味着该财产X可能永远得不到遵守;它意味着执行不是维护该财产的义务。你所声称的含义是,鼓励的秩序绝不会仅仅是一个错误的结论。((p)(P)Similarly,your implication of"that suggests foreach is intended to conserve order for sequential streams"because you saw an implementation that does in some case is equally imperror.(p)(P)In both cases,it seems like you're just uncomfortable with the fact that the specification givesa great deal of freedom.Specifically,it has the freedom to not preserve encounter order for sequential streams,even though that's what the implementation currently does,and further that it's kind of hard to image an implementation going out of it s way to process sequential sources out of order.但他说的是什么,他想说什么。(p)(P)That said,the wording of the comment about parallel streams is potentially confusing,because it is still possible to misinterpret it.The intent of calling out the parallel case explicitly here was educatical;the SPEC is still perfectly clear with that sentence removed entirely.然而,为了让人们了解谁是一个平行的群体,这将是不可接受的,以便不保证以下一点:将维护Encounter Order,因此,这一判决将补充到帮助Clarify the Motivation。但是,由于你不在,处理这类具体案件的决定仍然很有可能对Clarify Further有益。(p)