Endless Stream Parallel Processing in Java

Why doesn't the code below print any output, whereas if we remove the parallel, it prints 0, 1?

IntStream.iterate(0, i -> ( i + 1 ) % 2)
         .parallel()
         .distinct()
         .limit(10)
         .forEach(System.out::println);

Although I know that the ideal limit should be placed in front of a separate one, but my question is more related to the difference caused by the addition of parallel processing.

+11
source share
4 answers

The real reason is that ordered parallel .distinct()is a complete barrier operation described in the documentation:

distinct() (, ), .

" " , , . Stream API : .sorted() ( ) .distinct() ( ). , .distinct(), . .distinct() : . .distinct() , .

, @user140547 : .unordered() .distinct(), distinct() ( ConcurrentHashMap ). , .unordered() .distinct() .

+6

Stream.iterate " ". .

:

. , (distinct()) (Collectors.groupingBy()), , . , , limit(), , parallelism. , , , (), . , " " , .

, -, , unordered(), 0,1.

    IntStream.iterate(0, i -> (i + 1) % 2)
            .parallel()
            .unordered()
            .distinct()
            .limit(10)
            .forEach(System.out::println);
+4

, , , , .

fork join , , .

, , 10 .

, , , . java - .

+2

, : .distinct() 2 , , , . , , .

, - , . , :

, , . , , , , , , .

.

, : , 10, . , hasNext() = true, 0, 1, () - - , / , , .

() limit(), .

+1
source

All Articles