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.

package com.java.stream;

import java.util.concurrent.ForkJoinPool;

public class CheckPoolSize {

public static void main(String[] args) {

ForkJoinPool commonPool = ForkJoinPool.commonPool();
System.out.println(commonPool.getParallelism());
}
}

Output:3

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:

-Djava.util.concurrent.ForkJoinPool.common.parallelism=5

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.

package com.java.stream;

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();
list.stream().filter(s -> s.startsWith(“c”)).map(String::toUpperCase)
.forEach(System.out::println);
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)
.forEach(System.out::println);
long d = System.nanoTime();
System.out.println(“Time Taken for Parallel Stream:” + (d – c));
}
}

Output:
C2
C1
Time Taken for Sequential Stream:74966636
C1
C2
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 *