Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parallel sort in java8 returns invalid result

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?

like image 372
Muhammad Hewedy Avatar asked Feb 13 '23 03:02

Muhammad Hewedy


1 Answers

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);
like image 142
axtavt Avatar answered Feb 15 '23 17:02

axtavt