Skip to content

What Are Sequential And Parallel Streams

In this lesson, you will learn about the two different modes of streams with examples.

Gopi Gorantala
Gopi Gorantala
3 min read

Table of Contents

Types

Streams can be sequential or parallel. There are two main types/modes of stream operations.

  1. Sequential Streams
  2. Parallel Streams.

Sequential stream

Sequential streams are the default mode of operation for Java streams. When you work with a stream without explicitly specifying the processing mode, it operates in sequential mode. Sequential streams process elements one after another in a linear fashion, using a single thread.

In sequential stream processing, each element is processed in the order it appears in the stream. The operations on the stream are executed in a serial manner, meaning that each operation waits for the completion of the previous operation before proceeding to the next one. This guarantees that the elements are processed in a predictable and deterministic order.

Sequential streams are suitable for scenarios where the order of processing is important or when dealing with small to moderate-sized data sets. They can be used to perform operations such as filtering, mapping, sorting, and reducing collections of data in a sequential and straightforward manner.

Here's an example of using sequential streams to filter and map a list of integers:

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

public class SequentialStream {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

    int sum = numbers.stream()
            .filter(n -> n % 2 == 0)
            .mapToInt(n -> n * 2).sum();

    System.out.println(sum); // Output: 12
  }
}

In the above example, the stream operations (filter, mapToInt, and sum) are executed sequentially on a single thread. The elements are processed in the order they appear in the numbers list.

It's important to note that sequential streams do not provide any inherent parallelism or concurrency. They are designed for simple and linear processing of data. If you need to take advantage of multi-core processors and parallel processing, you can convert a sequential stream into a parallel stream using the parallelStream() method, as explained in the previous response.

Parallel Streams

Parallel streams are a feature of Java streams introduced in Java 8. They provide a convenient way to process data in parallel, taking advantage of multi-core processors and potentially improving performance for large data sets or computationally intensive operations.

Parallel streams allow the stream operations to be divided into multiple tasks that can be executed concurrently on multiple threads. This parallelization enables faster execution by leveraging the available processing power of the system. However, the order of execution is out of control. This is not in our control and changes every time we run the program.

To convert a sequential stream into a parallel stream, you can use the parallelStream() method instead of the regular stream() method on a collection or a stream source. This transformation splits the stream's data into multiple segments and processes them concurrently on separate threads.

We should only consider using parallel stream only when:

  1. You have massive items/objects to process.
  2. You want to reduce the overall time of execution of large sets of data.

Here's an example of using a parallel stream to filter and map a list of integers.

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

public class ParallelStream {
  public static void main(String[] args) {
    List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

    int sum = numbers.parallelStream()
            .filter(n -> n % 2 == 0)
            .mapToInt(n -> n * 2).sum();

    System.out.println(sum); // Output: 12
  }
}

In the above example, the parallelStream() method is used to convert the stream into a parallel stream. The rest of the stream operations (filter, mapToInt, and sum) remain the same as in the sequential example. The stream operations are divided into multiple tasks and executed concurrently on multiple threads, potentially improving the overall performance.

However, there is one downside when using parallel streams. If you can't handle them properly, they may lead to performance problems.

It's important to note that not all operations are suitable for parallel processing and some operations may actually perform worse when executed in parallel due to the overhead involved in managing multiple threads.

Therefore, it's important to carefully consider which operations to use in a parallel stream to ensure optimal performance.

Java Streams APIJava

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Differences Between JDK, JRE, and JVM?

Short answer JDK, JRE, and JVM are essential components of the Java platform, each serving a distinct purpose. Here are the key differences between them: 1. JDK (Java Development Kit): The JDK is used by developers to write, compile, and debug Java code. 2. JRE (Java Runtime Environment): End-users use

Members Public

Difference Between String and char[] in Java

Short answer Strings String is an object with many helpful methods. String class in Java's standard library is designed to handle text as a sequence of characters. A string of characters (string object) is non-modifiable or immutable in Java. Once you've created it, you cannot modify

Members Public

What is an Object class in Java?

Short answer Object class is the super class of every class you can create. In Java, a class extends another class using the keyword extends. If you don't have any other class to extend, that's fine. The compiler will make your class extend the Object class.