Parallel Streams in Java 8

Please read Java 8 Stream and Java 8 Stream part 2 before going through the below piece.

Streams can be executed in parallel to increase runtime performance on large amount of input elements.

Parallel streams use a common ForkJoinPool available via the static ForkJoinPool.commonPool() method. The size of the underlying thread-pool uses up to five threads – depending on the amount of available physical CPU cores.

Let us check the thread-pool size in the System.


import java.util.concurrent.ForkJoinPool;

public class CheckPoolSize {

public static void main(String[] args) {

ForkJoinPool commonPool = ForkJoinPool.commonPool();


In my System it is 3. It may vary for different Systems.

However, we can set the pool size in JVM parameter using the below:


The above program returns the Output as 5 after I set the JVM param.

Collections support the method parallelStream() to create a parallel stream of elements. Alternatively you can call the intermediate method parallel() on a given stream to convert a sequential stream to a parallel counterpart.

Let us take a look at the performance of Sequential Stream and parallel Stream in the below example.


import java.util.Arrays;
import java.util.List;

public class ParallelStreamExample {

public static void main(String[] args) {

List list =Arrays.asList(“a1”, “a2”, “b1”, “c2”, “c1”);
long a = System.nanoTime(); -> s.startsWith(“c”)).map(String::toUpperCase)
long b = System.nanoTime();
System.out.println(“Time Taken for Sequential Stream:” + (b – a));
long c = System.nanoTime();
list.parallelStream().filter(s -> s.startsWith(“c”)).map(String::toUpperCase)
long d = System.nanoTime();
System.out.println(“Time Taken for Parallel Stream:” + (d – c));

Time Taken for Sequential Stream:74966636
Time Taken for Parallel Stream:4514570

As observed from the above example, Parallel Stream was around 16 times faster than the Sequential Stream.

Leave a Reply

Your email address will not be published. Required fields are marked *