简体   繁体   English

Java的ArrayList.stream()。anyMatch()是否保证按顺序处理?

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

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 一旦元素返回true ,评估就会立即停止

Is this always true, or if not, is it at least for all common JDK implementations? 这总是如此,或者如果不是,至少对于所有常见的JDK实现是否都是如此?

Your question implies a concern about side-effects of stream operations, otherwise you wouldn't care about order or immediate termination. 您的问题意味着关注流操作的副作用 ,否则您不会关心订单或立即终止。 From the Javadoc : 来自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. 即使管道被约束产生的结果与流源的遭遇顺序一致(例如,IntStream.range(0,5).parallel()。map(x - > x * 2).toArray( )必须产生[0,2,4,6,8]),不保证映射器函数应用于单个元素的顺序,或者对给定元素执行任何行为参数的线程。

So the contract seems to be that you might get away with it but it's not guaranteed to work. 所以合同似乎是你可以侥幸逃脱,但它不能保证工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM