Вопрос

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