Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream parallel behaviour for allMatch, noneMatch, filter and map

I read in another post that after investigation it was found that the anyMatch terminal operation works in such a way that each thread (operating on a substream) periodically checks if other threads have found a result and if so, all other threads are stopped.

I assume, but wondered if someone could verify if noneMatch and allMatch also operate in this way, so if when running noneMatch, one thread finds an actual match, then the operation can return false. So do all other threads periodically check for this in the same manner described for anyMatch? Similary, does the inverse apply for allMatch?

Furthermore, I wondered if there was any difference when running the filter and map operations in parallel as to whether they are run on an ordered or unordered stream. On an ordered stream, I assume the most logical benefit is simply that the different threads can process each substream created and then merge them all back together in the same order. For an unordered stream, does this hold any advantages for such operations as I'm struggling to think of any?

like image 933
Tranquility Avatar asked Oct 29 '25 00:10

Tranquility


1 Answers

All three anyMatch, allMatch and noneMatch are implemented using the same MatchOps class with different flags set. So they work in pretty similar manner. All of them are short-circuiting and not ordered, so it does not matter whether your stream source is ordered or not: these operations will perform equally fast.

The operations like map and filter do not have any benefit with unordered source. Unordered source changes the algorithm for distinct, limit, skip, takeWhile (Java-9), dropWhile (Java-9). Seems that normal reduction (via reduce or collect) does not optimize the unordered case (though my very preliminary research suggests that such optimization would be possible).

like image 98
Tagir Valeev Avatar answered Oct 31 '25 22:10

Tagir Valeev