Java 8 – Parallel Streams

4 min read

Hey Guys!! In this post, we will be learning a very useful paradigm introduced in Java 8, parallel streams. A stream can execute sequentially as well as parallely. However, it is imperative to have understanding, when/ when not to use parallel stream and how it internally works!!

What is a parallel stream?

A parallel stream is used to split the source data into multiple parts, process parallely and combine the results.

How to create a parallel stream?

By using the parallel() operation in streams.

IntStream().rangeClosed(0,1000)
.parallel().sum();

The parallel() will split the stream into multiple parts and process them concurrently and then combine the result and return output.

Comparing performance of sequential vs parallel streams

public class ParallelStreamsExample {
    public static long checkPerformanceResult(
        Supplier<Integer> supplier, int noOfTimes) {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < noOfTimes; i++) {
            supplier.get();
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }

    public static int sequentialSum() {
        return IntStream.rangeClosed(0, 1000000)
                .sum();
    }

    public static int parallelSum() {
        return IntStream.rangeClosed(0, 1000000)
                .parallel()
                .sum();

    }

    public static void main(String[] args) {
        System.out.println("Sequential stream result "
                + checkPerformanceResult(ParallelStreamsExample::sequentialSum, 20));
        System.out.println("Parallel stream result "
                + checkPerformanceResult(ParallelStreamsExample::parallelSum, 20));
    }
}

The above example is just a illustration of how we can compare performances of sequential and parallel streams. There are possibilities when parallel stream are slower than sequential. Sometimes, spawning a thread and then combining the results are more time taking operations than processing sequentially. Therefore, we cannot assert that parallel streams will work faster than sequential.

How Parallel Stream works?

Parallel Streams uses the Fork/Join Framework introduced in JDK 7.
It creates multiple threads for concurrent processing. No of threads spawned is equal to number of processors available in machine.

The fork/join framework is designed to recursively split a parallelizable task into smaller tasks and then combine the results of each subtask to produce the overall result.

It’s an implementation of the ExecutorService interface, which distributes those subtasks to worker threads in a thread pool, called ForkJoinPool.

Relevant posts:

  1. Stream API Introduction
  2. Stream API Operations – Part 1
  3. Java Lambda Functional Interfaces
  4. Stream API Operations – Part 2
  5. Java Lambda Expressions- Basics