Java的ArrayList.stream().anyMatch()是否保证按顺序进行处理? [英] Does Java's ArrayList.stream().anyMatch() guarantee in-order processing?

查看:389
本文介绍了Java的ArrayList.stream().anyMatch()是否保证按顺序进行处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

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

但是我也想保证:

  • 列表从第一个元素到最后一个元素按顺序处理;
  • 一旦元素返回true,评估就会立即停止

这是否总是对的,或者至少对所有常见的JDK实现都是如此?

解决方案

您的问题暗含着对流操作的副作用的担忧,否则您将不必担心订单或立即终止.来自 Javadoc :

副作用

通常不鼓励流操作的行为参数产生副作用,因为它们经常会导致无意识地违反无状态要求以及其他线程安全危害.

如果行为参数确实具有副作用,除非明确说明,否则不能保证这些副作用对于其他线程的可见性,也不能保证对相同"的操作是不同的.同一流管道中的元素在同一线程中执行.此外,这些效果的排序可能令人惊讶.即使当管道被约束以产生与流源的遇到顺序一致的结果时(例如,IntStream.range(0,5).parallel().map(x-> x * 2).toArray) ()必须产生[0、2、4、6、8]),对于映射器函数应用于单个元素的顺序或给定元素执行任何行为参数的顺序,不做任何保证.

所以合同似乎是您可能会摆脱它,但不能保证正常工作.

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?

解决方案

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.

这篇关于Java的ArrayList.stream().anyMatch()是否保证按顺序进行处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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