Understanding Sequential and Parallel Streams in Java

Posted By : Anil Kumar Maurya | 29-Sep-2018

Java has given a very good feature that can parallelize stream operations to leverage multi-core systems. This blog provides a perspective and shows how the parallel stream can improve performance.

 

In Java, a stream is a sequence of objects represented as a channel of data. Usually, the data is situated at a source and transmitted to a destination. A stream is not a repository rather it operates on a data source such as on an array or a collection. So basically, the bits which are currently passing are called the stream.

 

In Java, any stream operation is processed sequentially by default, unless explicitly specified as parallel. The main disadvantage of sequential streams is that they never use the multicore system.  What happens, when we apply multithreading to process the stream? It will operate on a single core at a time. For example, if we are processing in four different threads versus four different cores is obviously different where they both have no match with one another. We will understand this phenomenon with below example.

package com.test.main;

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

public class MainApp {
   public static oid main(String[] args) {
      List list=Arrays.asList(1,2,3,4,5,6,7,8,9);
      list.stream().forEach(System.out::print);
      System.out.println();
      list.parallelStream().forEach(System.out::print);
   }
}

Output:
123456789
685347129


The above example is an illustration of a sequential stream as well as a parallel stream in operation. The list.stream() works in sequence on a single thread with the println() operation while list.parallelStream() is processed in parallel. This is taking full advantage of the underlying multicore environment.


Parallel stream leverage multicore processors which results in a substantial increase in performance. They are complex and error-prone. But, the Java stream library provides the ability to do it easily. Using java stream libraries are reliable. We can use it in a very simple way, we only have to invoke a few methods and the rest is taken care of. We can do it in a couple of ways. First one is to obtain a parallel stream by invoking the parallelStream() method defined by Collection. The second one is to invoke the parallel() method defined by BaseStream on a sequential stream.

About Author

Author Image
Anil Kumar Maurya

Anil is an experienced Lead with core knowledge of Java, Spring, and SQL. He has good working experience in banking, finance and trading domain.

Request for Proposal

Name is required

Comment is required

Sending message..