Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallelism and Flatmap in Java 8 Streams

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);
like image 330
Benedikt Bünz Avatar asked Jun 25 '14 14:06

Benedikt Bünz


People also ask

What is parallel stream in java8?

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.

Is Java 8 support parallel and sequential streams?

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.

Are Java streams run in parallel?

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.


1 Answers

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).

like image 110
Daniel Hári Avatar answered Oct 09 '22 05:10

Daniel Hári