I have a question about the following two codes.
Without parallelism:
Stream.of(1, 2, 3)
.peek(System.out::println)
.skip(1)
.map(n-> n * 10)
.forEach(System.out::println);
The output is:
1
2
20
3
30
With parallelism:
Stream.of(1, 2, 3)
.parallel()
.peek(System.out::println)
.skip(1)
.map(n-> n * 10)
.forEach(System.out::println);
Output is:
2
3
20
30
Why does the output of the parallel stream not include 1?
CodePudding user response:
There's nothing wrong with skip()
, you've asked to skip 1
element, and it always does so. The stream created by Stream.of()
is ordered and skip()
gives a guarantee that encounter order would always be taken into account.
is constrained to skip not just any
n
elements, but the firstn
elements in the encounter order.
Because we don't see 10
in the output, that's the proof that skip()
does is job correctly - element 1
never reaches the terminal operation.
There's no output from peek()
in parallel (1
is not printed).
This method operates via side effects and according to the API note "exists mainly to support debugging". Contrary to forEach()
/forEachOrdered()
it's an intermediate operation which is not meant to perform the resulting action. API documentation warns that it could be elided, and you shouldn't rely on it.
The eliding of side-effects may also be surprising. With the exception of terminal operations
forEach
andforEachOrdered
, side-effects of behavioral parameters may not always be executed when the stream implementation can optimize away the execution of behavioral parameters without affecting the result of the computation.
CodePudding user response:
well the stream is ordered, so if you will iterate 1,2,3,4 the result will be 1,2,3,4 but if you use parallel or parallelStream this will be execute in other order. e.j: Stream.of(1,2,3,4).parallel().foreach(System.out::println) the output can be in any order.