parallel processing with infinite stream in Java

后端 未结 4 1873
夕颜
夕颜 2020-12-31 10:05

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

IntStream.iterate(0, i -> ( i + 1 ) % 2)
         .parallel()
         


        
4条回答
  •  天涯浪人
    2020-12-31 10:35

    Stream.iterate returns 'an infinite sequential ordered Stream'. Therefore, making a sequential stream parallel is not too useful.

    According to the description of the Stream package:

    For parallel streams, relaxing the ordering constraint can sometimes enable more efficient execution. Certain aggregate operations, such as filtering duplicates (distinct()) or grouped reductions (Collectors.groupingBy()) can be implemented more efficiently if ordering of elements is not relevant. Similarly, operations that are intrinsically tied to encounter order, such as limit(), may require buffering to ensure proper ordering, undermining the benefit of parallelism. In cases where the stream has an encounter order, but the user does not particularly care about that encounter order, explicitly de-ordering the stream with unordered() may improve parallel performance for some stateful or terminal operations. However, most stream pipelines, such as the "sum of weight of blocks" example above, still parallelize efficiently even under ordering constraints.

    this seems to be the case in your case, using unordered(), it prints 0,1.

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

提交回复
热议问题