Consider the following example:
IntStream.of(-1, 1)
.parallel()
.flatMap(i->IntStream.range(0,1000).parallel())
.forEach(System.out::println);
Does it matter whether I set the inner flag to parallel? The results look very similar if I leave it away or not.
Also why does the code (ReferencePipeline
) sequentialize the mapping?
I am confused by the line:
result.sequential().forEach(downstream);
Java Parallel Streams is a feature of Java 8 and higher, meant for utilizing multiple cores of the processor. Normally any java code has one stream of processing, where it is executed sequentially.
Parallel streams divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. On the other hand sequential streams work just like for-loop using a single core.
Parallel Streams. Any stream in Java can easily be transformed from sequential to parallel. We can achieve this by adding the parallel method to a sequential stream or by creating a stream using the parallelStream method of a collection: List<Integer> listOfNumbers = Arrays.
In the current JDK (jdk1.8.0_25), the answer is no, it doesn't matter you set the inner flag to parallel, because even you set it, the .flatMap() implementation set's back the stream to sequential here:
result.sequential().forEach(downstream);
("result" is the inner stream and it's sequential() method's doc says: Returns an equivalent stream that is sequential. May return itself, either because the stream was already sequential, or because the underlying stream state was modified to be sequential.)
In most cases there could be no effort to make the inner stream parallel; if outer stream has at least same number of items as number of threads that can run parallel (ForkJoinPool.commonPool().getParallelism() = 3
in my computer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With