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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top