Stop 09 · Lambdas & StreamsTopics · 7/7

Parallel Streams

Part of the Java Roadmap

In short

Your laptop probably has eight or more CPU cores, and a normal stream uses one. parallelStream() can share the work across all of them, but only some jobs get faster, and some get wrong answers.

parallelStream() splits work across CPU cores using the common ForkJoinPool. It can speed up large CPU-bound tasks but often slows down small ones and is unsafe with shared mutable state.

The jaadu and three helpers sit around a big sack, each shelling a separate pile of peas into their own bowl.

Think of it like this

Shelling peas with friends

One person shelling a sack of peas takes an hour. Four friends each take a quarter and finish in fifteen minutes, plus a minute to split and recombine. For a single handful, splitting takes longer than just doing it. And if all four grab the same bowl at once, peas end up on the floor.

Watch it happen

When to go parallel

Sequential stream

  • One thread, predictable order
  • Best for small lists and quick operations
  • Safe with most code
  • The default, and usually right

Parallel stream

  • Splits work across the common ForkJoinPool
  • Helps for large, CPU-heavy, independent work
  • Splitting and merging has a cost
  • Breaks with shared mutable state

Start sequential. Go parallel only after measuring, on big data, with pure functions and an easily split source like an array or range.

The big ideas

What you need to know

Common ForkJoinPool

Parallel streams share one pool sized to your cores minus one. A blocking task there slows every parallel stream in the app.

Splittable sources

ArrayList, arrays and IntStream.range split cheaply. LinkedList and Files.lines split badly and gain little.

No shared mutation

Never add to an outside ArrayList from a parallel forEach. Let collect() or toList() build the result safely.

Measure, don't guess

Time both versions on realistic data. Use JMH for serious benchmarks, since the JIT warm-up fools simple timers.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.List;3import java.util.stream.LongStream;4 5public class ParallelDemo {6    static boolean isPrime(long n) {7        if (n < 2) return false;8        for (long i = 2; i * i <= n; i++) {9            if (n % i == 0) return false;10        }11        return true;12    }13 14    public static void main(String[] args) {15        long count = LongStream.rangeClosed(1, 5_000_000)16                .parallel()17                .filter(ParallelDemo::isPrime)18                .count();19        System.out.println("Primes: " + count);20 21        // WRONG: many threads adding to one ArrayList22        List<Long> unsafe = new ArrayList<>();23        LongStream.range(0, 10_000).parallel().forEach(unsafe::add);24 25        // RIGHT: let the stream build the list26        List<Long> safe = LongStream.range(0, 10_000).parallel()27                .boxed()28                .toList();29        System.out.println(unsafe.size() + " vs " + safe.size());30    }31}

1/4isPrime only looks at its own input. A pure function like this is safe to run on many threads.

Counting primes is CPU-heavy and independent per number, a good fit for parallel. The unsafe list often ends up short or throws an exception.

Save yourself the pain

Common mistakes

Oops

Adding .parallel() to every stream to 'make it faster'.

Do this instead

For a few thousand cheap items it is usually slower. Measure first.

Oops

Calling a slow REST API or database inside a parallel stream.

Do this instead

That blocks the shared ForkJoinPool. Use an ExecutorService or virtual threads for I/O-heavy work.

Oops

Expecting forEach to print in order on a parallel stream.

Do this instead

Order is not guaranteed. Use forEachOrdered if order matters, accepting some lost speed.

Your mission

Time it yourself

~25 min

Quick check

Which job is the best candidate for a parallel stream?

Go deeper

  1. 1Time a large computation with stream() and parallelStream().
  2. 2Try it on a small list and notice the overhead.
  3. 3Never modify a shared collection from inside a parallel stream.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge