Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 223
Petr Hudeček Avatar asked Jul 10 '16 06:07

Petr Hudeček


1 Answers

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.

like image 169
Jim Garrison Avatar answered Oct 28 '22 11:10

Jim Garrison