Does Java's ArrayList.stream().anyMatch() guarantee in-order processing?

穿精又带淫゛_ 提交于 2020-01-23 07:07:07

问题


I have this code:

ArrayList<Detector> detectors;
detectors.stream().anyMatch(d -> d.detectRead(impendingInstruction, fieldName));

But I would also like to have guarantees that:

  • The list is processed in order, from the first element to the last;
  • As soon an element returns true, evaluations stops immediately

Is this always true, or if not, is it at least for all common JDK implementations?


回答1:


Your question implies a concern about side-effects of stream operations, otherwise you wouldn't care about order or immediate termination. From the Javadoc:

Side-effects

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

If the behavioral parameters do have side-effects, unless explicitly stated, there are no guarantees as to the visibility of those side-effects to other threads, nor are there any guarantees that different operations on the "same" element within the same stream pipeline are executed in the same thread. Further, the ordering of those effects may be surprising. Even when a pipeline is constrained to produce a result that is consistent with the encounter order of the stream source (for example, IntStream.range(0,5).parallel().map(x -> x*2).toArray() must produce [0, 2, 4, 6, 8]), no guarantees are made as to the order in which the mapper function is applied to individual elements, or in what thread any behavioral parameter is executed for a given element.

So the contract seems to be that you might get away with it but it's not guaranteed to work.



来源:https://stackoverflow.com/questions/38289399/does-javas-arraylist-stream-anymatch-guarantee-in-order-processing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!