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

Gopi Gorantala Twitter

Gopi is a highly experienced Full Stack developer with a deep understanding of Java, Microservices, and React. He worked in India & Europe for startups, the EU government, and tech giants.

Comments


Related Posts

Members Public

How To Write Lambda Expressions

This lesson introduces the basic lambda expression structure with tips to write efficient code.

Members Public

What Are Lambda Expressions?

This is an introductory lesson on lambda expressions. You will learn about the lambda operator, expression, syntaxes and more!

Members Public

Power Of Two (Exercise Problem)

This is an exercise problem for your practice. Try to come up with an approach and solve it by yourself. Good Luck!