Search code examples
javamultithreadingjava-streamjava.util.concurrent

when do we really benfit from java stream.unordered()?


java streams has this method unordered().

I am not sure when this method will really enhance the performance of the program.

  1. someList.stream.unordered() //here List is any way ordered and using unordered() is not going to make the list unordered, so the usage of unordered() has no effect.

  2. someSet.stream.unordered() //here set is any way NOT ordered and hence using unordered() is not going to make the set any further unordered, so the uage of unordered() has no effect. Similarly for Map too.

While using parallelStream it may help though. But otherwise for NON parallelStream's is it required. Are there any such cases where it will boost performance.


Solution

  • A per the documentation on stream ordering (emphasis mine):

    For parallel streams, relaxing the ordering constraint can sometimes enable more efficient execution. Certain aggregate operations, such as filtering duplicates (distinct()) or grouped reductions (Collectors.groupingBy()) can be implemented more efficiently if ordering of elements is not relevant. Similarly, operations that are intrinsically tied to encounter order, such as limit(), may require buffering to ensure proper ordering, undermining the benefit of parallelism. In cases where the stream has an encounter order, but the user does not particularly care about that encounter order, explicitly de-ordering the stream with unordered() may improve parallel performance for some stateful or terminal operations.