문제

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