search for example of inconsistent behavior java-8 stream?

前端 未结 2 1286
梦如初夏
梦如初夏 2020-12-06 22:28

In java 8 documentation (doc order stream), one can see this :

if [a stream] is not ordered, repeated execution might produce different results.

2条回答
  •  醉酒成梦
    2020-12-06 23:11

    the documentation of Stream#forEach is already said as below:

    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.

    so the following test should be pass:

    List ordered = Arrays.asList(1, 2, 3, 4);
    List unordered = new CopyOnWriteArrayList<>();
    
    ordered.stream().parallel().forEach(unordered::add);
    
    assertThat(unordered, not(equalTo(ordered)));
    

    and the operation Stream#findAny also is nondeterministic.

提交回复
热议问题