When I apply a parallel sort using streams in Java 8, I get an invalid result:
List<String> list = new ArrayList<>();
list.add("A");
list.add("C");
list.add("B");
list.stream().sorted().forEach(System.out::println);
System.out.println("-");
list.stream().parallel().sorted().forEach(System.out::println);
Results:
A
B
C
-
B <----- Invalid order
C
A
Why does the parallel sort return unsorted results?
forEach()
doesn't guarantee to process elements in specific order:
The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.
You should use forEachOrdered()
instead:
list.stream().parallel().sorted(Comparator.comparing(e -> e.getFirstName()))
.forEachOrdered(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With