00:00

Stream vs Parallel Stream in Java

Last updated:

A sequential stream processes its elements one after another on the calling thread. A parallel stream splits its source into parts, processes the parts on several threads of the common ForkJoinPool, and combines the partial results. Both are the same java.util.stream.Stream type, introduced in Java 8; the execution mode is a property of the pipeline.

You get a sequential stream from collection.stream() and a parallel one from collection.parallelStream() or by calling parallel() on any stream. This tutorial shows how the two modes differ in threads, ordering, correctness and speed.

1. Syntax and Method Signatures

BaseStream.java and Collection.java (API)
// java.util.Collection (Java 8)
default Stream<E> stream()
default Stream<E> parallelStream()

// java.util.stream.BaseStream (Java 8)
S parallel()          // returns an equivalent parallel stream
S sequential()        // returns an equivalent sequential stream
boolean isParallel()  // true if a terminal operation would run in parallel

S is the stream type itself, such as Stream<T> or IntStream. Both parallel() and sequential() are intermediate operations that set a flag for the whole pipeline; the last call wins.

2. How Sequential and Parallel Streams Run

When the terminal operation of a parallel pipeline runs, the source's Spliterator splits the data into smaller chunks. Each chunk becomes a task in the common ForkJoinPool, and the calling thread helps with the work. When the tasks finish, their partial results are combined, for example by adding partial sums or merging partial lists.

Splitting and combining are the reasons parallel streams are not automatically faster. Arrays, ArrayList and IntStream.range() split cheaply; LinkedList and Stream.iterate() split poorly. The common pool has, by default, one thread fewer than the number of available processors, and it is shared by every parallel stream in the JVM.

Sequential and parallel execution of the same pipeline Sequential: the elements 1 to 8 are processed one by one on the main thread and produce one result. Parallel: the source is split into two chunks, 1 to 4 and 5 to 8; worker threads process the chunks at the same time and produce partial results, which are combined into one result. SOURCE PROCESS RESULT Sequential 1 2 3 4 5 6 7 8 main thread one result Parallel part 1 1 2 3 4 worker thread A partial result Parallel part 2 5 6 7 8 worker thread B partial result Combine partial + partial
Figure 1: A sequential stream walks the whole source on one thread. A parallel stream splits the source, processes the parts on worker threads and combines the partial results.

3. Java Examples

Example 1: The same result in both modes

Count the numbers between 1 and 2,000,000 whose digit sum is divisible by 7, sequentially and in parallel.

SameResultBothModes.java
import java.util.stream.IntStream;

public class SameResultBothModes {

    static int digitSum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        long sequential = IntStream.rangeClosed(1, 2_000_000)
                .filter(n -> digitSum(n) % 7 == 0)
                .count();

        long parallel = IntStream.rangeClosed(1, 2_000_000)
                .parallel()
                .filter(n -> digitSum(n) % 7 == 0)
                .count();

        System.out.println("Sequential count: " + sequential);
        System.out.println("Parallel count:   " + parallel);
    }
}
Output
Sequential count: 285773
Parallel count:   285773

How it works: The filter depends only on each number, and counting is associative, so both modes must agree. The parallel version splits the range across worker threads and adds up their counts.

Example 2: Ordering with forEach() and forEachOrdered() (Java 9+)

Print five invoice numbers from a parallel stream, first with forEach(), then with forEachOrdered().

ParallelOrdering.java
import java.util.List;

public class ParallelOrdering {

    public static void main(String[] args) {
        List<String> invoices = List.of("INV-1", "INV-2", "INV-3", "INV-4", "INV-5");

        System.out.print("forEach:        ");
        invoices.parallelStream().forEach(id -> System.out.print(id + " "));
        System.out.println();

        System.out.print("forEachOrdered: ");
        invoices.parallelStream().forEachOrdered(id -> System.out.print(id + " "));
        System.out.println();
    }
}
Output
forEach:        INV-5 INV-2 INV-1 INV-4 INV-3
forEachOrdered: INV-1 INV-2 INV-3 INV-4 INV-5

The first line changes from run to run; the line above is one real run. The second line is always in order.

How it works: forEach() on a parallel stream runs the action on whichever thread finishes first, so the order is not guaranteed. forEachOrdered() respects the list's encounter order, at the cost of some parallelism.

Example 3: The last parallel() or sequential() call wins

Check which mode a pipeline runs in after switching back and forth.

LastCallWins.java
import java.util.stream.Stream;

public class LastCallWins {

    public static void main(String[] args) {
        Stream<String> a = Stream.of("x", "y", "z");
        System.out.println("plain:                  " + a.isParallel());

        Stream<String> b = Stream.of("x", "y", "z").parallel();
        System.out.println("parallel():             " + b.isParallel());

        Stream<String> c = Stream.of("x", "y", "z").parallel().map(String::toUpperCase).sequential();
        System.out.println("parallel()...sequential(): " + c.isParallel());
    }
}
Output
plain:                  false
parallel():             true
parallel()...sequential(): false

How it works: The mode is one flag for the entire pipeline, not per step. You cannot make only the map() parallel: the final call before the terminal operation decides how every step runs.

Example 4: Shared mutable state breaks in parallel

Collect the even numbers from 1 to 10,000. Adding to a plain ArrayList from a parallel lambda is unsafe; collecting is safe.

SafeParallelCollect.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SafeParallelCollect {

    public static void main(String[] args) {
        List<Integer> evens = IntStream.rangeClosed(1, 10_000)
                .parallel()
                .filter(n -> n % 2 == 0)
                .boxed()
                .collect(Collectors.toList());

        System.out.println("Size:  " + evens.size());
        System.out.println("First: " + evens.get(0) + ", last: " + evens.get(evens.size() - 1));
    }
}
Output
Size:  5000
First: 2, last: 10000

How it works: Each worker thread collects into its own temporary list, and the lists are merged in encounter order, so the result is complete and ordered. Writing list.add(n) inside forEach() on a parallel stream instead can lose elements or throw ArrayIndexOutOfBoundsException, because ArrayList is not thread-safe.

4. Sequential vs Parallel Stream Comparison

AspectSequential streamParallel stream
Created withstream(), Stream.of()parallelStream() or .parallel()
ThreadsThe calling threadCommon ForkJoinPool workers plus the caller
forEach() orderEncounter order (in practice)Unpredictable; use forEachOrdered()
findAny()Usually the first elementAny element
Shared mutable stateRisky but often worksGives wrong results or exceptions
OverheadNoneSplitting, task scheduling and combining
Best forSmall or medium data, I/O, ordered workLarge data, CPU-heavy, independent operations

Both modes must produce the same result for a correct pipeline. If they do not, the pipeline has a side effect or an operation that is not associative. See Parallel Stream Introduction and Sequential vs Parallel Performance.

5. Real-World Use Cases

  • Sequential for everyday code: filtering a page of orders, mapping DTOs or building a response is small work where sequential streams are simplest and fastest.
  • Parallel for large CPU-bound batches: scoring millions of transactions for fraud rules or computing statistics over a big in-memory array.
  • Sequential for I/O: calling a database or REST service per element blocks threads in the shared pool; use an executor or virtual threads instead.

6. Important Points

  • Associativity matters. reduce() in parallel needs an associative function; subtraction, for example, gives different answers.
  • Encounter order is kept by toList(), collect(), findFirst() and forEachOrdered(), even in parallel.
  • The common pool is shared. A slow, blocking lambda in one parallel stream slows down every other parallel stream in the application.
  • Exceptions thrown in a worker thread are rethrown from the terminal operation on the calling thread.
  • Small inputs are usually slower in parallel; the break-even point depends on the work per element, so measure.

7. Common Mistakes and Best Practices

Updating a shared counter

Wrong
int[] total = {0};
orders.parallelStream().forEach(o -> total[0] += o.amount());   // lost updates

Let the stream combine the values instead:

ParallelSumFix.java
import java.util.stream.IntStream;

public class ParallelSumFix {

    public static void main(String[] args) {
        int total = IntStream.rangeClosed(1, 100_000)
                .parallel()
                .map(n -> n % 50)
                .sum();

        System.out.println("Total: " + total);
    }
}
Output
Total: 2450000

Other mistakes to avoid

  • Making everything parallel. Start sequential and switch only after a benchmark shows a gain.
  • Using parallel() with LinkedList or Stream.iterate(). These sources split badly.
  • Relying on findAny() returning the first element. Use findFirst() when position matters.
  • Blocking calls inside a parallel stream. Network or database calls tie up shared pool threads.

8. Summary

  • Sequential streams run on the calling thread; parallel streams split the source across the common ForkJoinPool.
  • parallel() and sequential() set the mode of the whole pipeline, and the last call wins.
  • A correct pipeline gives the same result in both modes; shared mutable state and non-associative functions break that.
  • Use forEachOrdered() or ordered collectors when order matters in parallel.
  • Prefer sequential streams by default and measure before going parallel.

9. References