Skip to lesson

A parallel stream splits its elements into chunks, works on the chunks at the same time on several CPU cores, and then combines the partial results. You turn it on with one call, parallelStream() or parallel(), but the result stays correct only when the lambdas follow a few strict rules.

parallelStream and parallel: splitting the work

A parallel stream splits its elements across several threads to process them at the same time. It helps only for large, independent work.

A modern laptop has 4 to 16 cores, and each core can run one thread at a time. A normal stream uses only one of them. list.parallelStream() starts a parallel stream from a collection, and stream.parallel() switches an existing pipeline to parallel.

A parallel stream splits the numbers 1 to 8 into four chunks. Four threads each add their own two numbers: 3, 7, 11 and 15. The partial results are then combined into the final sum 36.

Example 1 · Same answer, sequential or parallel

ParallelBasicsDemo.javaJava
import java.util.List;import java.util.stream.IntStream;import java.util.stream.LongStream;
public class ParallelBasicsDemo {    public static void main(String[] args) {        long seq = LongStream.rangeClosed(1, 10_000_000).sum();        long par = LongStream.rangeClosed(1, 10_000_000).parallel().sum();        System.out.println("Sequential sum: " + seq);        System.out.println("Parallel sum:   " + par);
        List<Integer> fees = List.of(42000, 38000, 45000, 40000, 39000);        int total = fees.parallelStream().mapToInt(Integer::intValue).sum();        System.out.println("Total fees: " + total);
        System.out.println("list.stream() parallel?         " + fees.stream().isParallel());        System.out.println("list.parallelStream() parallel? " + fees.parallelStream().isParallel());        System.out.println("parallel() then sequential()?   "                + IntStream.range(0, 10).parallel().filter(i -> i > 2).sequential().isParallel());    }}
Output
Sequential sum: 50000005000000
Parallel sum:   50000005000000
Total fees: 204000
list.stream() parallel?         false
list.parallelStream() parallel? true
parallel() then sequential()?   false

What this code does

  • The sum is split into chunks, each chunk is added on its own thread, and the chunk totals are added at the end. Because + is associative, the answer is exactly the same as the sequential one.
  • The mode applies to the whole pipeline, and the last call wins: parallel() followed by sequential() gives a fully sequential stream.
  • Why parallel here: adding is independent for each chunk, and the numbers are many. The same pipeline on a handful of values would be slower, because splitting costs time.

isParallel() tells you which mode a stream is in. The mode belongs to the whole pipeline, not to one step. If a pipeline calls both parallel() and sequential(), the last call wins for every step. You cannot run filter in parallel and map sequentially in the same pipeline.

Under the hood, the source is cut in half, then each half is cut again, until the chunks are small. Each chunk runs the pipeline on its own thread. Then the partial results are joined in pairs, in the original order, until one result is left. This "split, work, join" model is called fork/join. The object that knows how to cut a source is its Spliterator, short for "splitting iterator".

Order of execution

How a parallel stream runs

Put the stages of a parallel sum in the order they happen.

The common ForkJoinPool shared by all parallel streams

Parallel streams do not create new threads each time. They borrow threads from one shared thread pool, a group of ready threads that take tasks from a queue. This pool is ForkJoinPool.commonPool(), and every parallel stream in the whole program uses it.

Example 2 · Watching forEach run on several threads

ThreadsDemo.javaJava
import java.util.concurrent.ForkJoinPool;import java.util.stream.IntStream;
public class ThreadsDemo {    public static void main(String[] args) {        System.out.println("Cores: " + Runtime.getRuntime().availableProcessors());        System.out.println("Common pool threads: " + ForkJoinPool.commonPool().getParallelism());
        IntStream.rangeClosed(1, 8)                .parallel()                .forEach(i -> System.out.println("Roll " + i + " on " + Thread.currentThread().getName()));    }}
Sample output (cores, threads and order differ on every computer and run)
Cores: 12
Common pool threads: 11
Roll 6 on main
Roll 5 on main
Roll 8 on main
Roll 7 on main
Roll 3 on ForkJoinPool.commonPool-worker-1
Roll 4 on ForkJoinPool.commonPool-worker-1
Roll 2 on ForkJoinPool.commonPool-worker-1
Roll 1 on ForkJoinPool.commonPool-worker-1

What this code does

  • The roll numbers come out in a mixed order, and the work is shared between main and the ForkJoinPool.commonPool-worker threads. Run it twice and the order changes.
  • The pool size is the number of cores minus one; the main thread that started the stream works too.

By default the pool has one thread fewer than the number of cores, and the thread that started the stream, often main, helps with the work too. On an 8-core machine, about 8 threads work on a parallel stream in total. You can read the pool size with ForkJoinPool.commonPool().getParallelism(). Sharing has a cost. If one part of a web server runs a slow parallel stream, the other parallel streams in the same server wait for free threads. That is why parallel streams suit short, CPU-heavy work, and never long waits such as network calls, which the next lesson covers.

The pool size can be changed for the whole program with the system property java.util.concurrent.ForkJoinPool.common.parallelism, but that affects every parallel stream, so it is rarely the right fix.

Order: forEach versus forEachOrdered, findAny versus findFirst

A list has an encounter order: the order in which its elements come out, first to last. A parallel stream keeps this order for the result where it can: toList(), collect, findFirst and reduce all give the same answer as a sequential stream.

Example 3 · Order you can rely on

OrderDemo.javaJava
import java.util.List;import java.util.stream.IntStream;
public class OrderDemo {    public static void main(String[] args) {        System.out.print("forEachOrdered: ");        IntStream.rangeClosed(1, 10).parallel().forEachOrdered(i -> System.out.print(i + " "));        System.out.println();
        List<Integer> evens = IntStream.rangeClosed(1, 20).parallel().filter(i -> i % 2 == 0).boxed().toList();        System.out.println("toList keeps order: " + evens);
        List<Integer> marks = List.of(72, 35, 88, 29, 64, 31, 90);        int firstFail = marks.parallelStream().filter(m -> m < 40).findFirst().get();        int anyFail = marks.parallelStream().filter(m -> m < 40).findAny().get();        System.out.println("findFirst: " + firstFail);        System.out.println("findAny gave a failing mark? " + (anyFail < 40));    }}
Output
forEachOrdered: 1 2 3 4 5 6 7 8 9 10
toList keeps order: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
findFirst: 35
findAny gave a failing mark? true

What this code does

  • forEachOrdered and toList() follow the encounter order even in parallel, so this output is the same on every run.
  • findFirst is always 35, the first failing mark in the list. findAny may return 35, 29 or 31, depending on which thread finds one first, so the program only checks that it is a failing mark.

Two operations do not promise order. forEach runs the action on each element as soon as some thread gets to it, so a parallel forEach prints in a mixed order. forEachOrdered waits and runs the actions in encounter order, which costs some speed. findAny returns whichever matching element a thread finds first, while findFirst always returns the first match in encounter order. So choose by meaning. "Any failed payment will do, to raise an alert" is findAny. "The first student in roll order who failed" is findFirst. A HashSet has no encounter order at all, so order was never promised there.

Thread safety rules for lambdas in parallel streams

Several threads run your lambdas at the same time, so the lambdas must not step on each other. The next two examples show what goes wrong and the thread-safe fix.

Example 4 · Trap: reduce with subtraction or a wrong identity

ReduceTrapDemo.javaJava
import java.util.stream.IntStream;
public class ReduceTrapDemo {    public static void main(String[] args) {        // subtraction is not associative: (10 - 5) - 2 is not 10 - (5 - 2)        System.out.println("Sequential 1-2-...-10: " + IntStream.rangeClosed(1, 10).reduce(0, (a, b) -> a - b));        System.out.println("Parallel   1-2-...-10: " + IntStream.rangeClosed(1, 10).parallel().reduce(0, (a, b) -> a - b));
        // 10 is not an identity for +: it is added once for every chunk        System.out.println("Sequential with identity 10: " + IntStream.rangeClosed(1, 10).reduce(10, Integer::sum));        System.out.println("Parallel with identity 10:   " + IntStream.rangeClosed(1, 10).parallel().reduce(10, Integer::sum));
        // fix: identity 0, and add the extra 10 once at the end        System.out.println("Fixed: " + (IntStream.rangeClosed(1, 10).parallel().sum() + 10));    }}
Sample output (the two wrong parallel lines can differ on your computer)
Sequential 1-2-...-10: -55
Parallel   1-2-...-10: -5
Sequential with identity 10: 65
Parallel with identity 10:   155
Fixed: 65

What this code does

  • Each chunk starts from the identity and is reduced on its own, then the chunk results are combined with the same function. With subtraction, combining chunks flips signs; with identity 10, the 10 is added once per chunk, ten times in the sample run shown.
  • The wrong numbers depend on how many chunks your machine makes, so this bug can pass on a laptop and fail on a server. Only an associative function with a true identity gives one fixed answer.

Example 5 · Thread-safe ways to count and total

SafeTotalsDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.concurrent.atomic.AtomicLong;import java.util.stream.Collectors;import java.util.stream.IntStream;
record Txn(String bank, int amount) { }
public class SafeTotalsDemo {    public static void main(String[] args) {        List<Txn> txns = IntStream.rangeClosed(1, 30_000)                .mapToObj(i -> new Txn(i % 3 == 0 ? "SBI" : i % 3 == 1 ? "HDFC" : "ICICI", i % 500))                .toList();
        // works, but every thread fights over one shared counter        AtomicLong shared = new AtomicLong();        txns.parallelStream().forEach(t -> shared.addAndGet(t.amount()));        System.out.println("AtomicLong total: " + shared.get());
        // better: no shared state at all        long total = txns.parallelStream().mapToLong(Txn::amount).sum();        System.out.println("sum() total:      " + total);
        Map<String, Long> perBank = txns.parallelStream()                .collect(Collectors.groupingBy(Txn::bank, TreeMap::new, Collectors.summingLong(Txn::amount)));        System.out.println("Per bank: " + perBank);    }}
Output
AtomicLong total: 7485000
sum() total:      7485000
Per bank: {HDFC=2495000, ICICI=2495000, SBI=2495000}

What this code does

  • An AtomicLong is a number holder that many threads can update safely, so the total is right. But all threads must take turns on that one value, which wastes most of the parallel speed.
  • mapToLong(...).sum() and groupingBy give each thread its own partial result and merge them at the end. They are correct, faster, and say what they compute.

Four rules keep a parallel stream correct.

  • Stateless: a lambda must not remember anything between elements, such as a seen set or a running total.
  • No shared changes: never change an outside list, map, field or counter. Let toList, sum, count and collectors build the result.
  • Non-interfering: never change the source collection while the stream runs.
  • Associative reduce with a true identity: (a op b) op c must equal a op (b op c), and the identity must change nothing, such as 0 for +. Subtraction fails the first rule; 10 as the identity of a sum fails the second, because it is added once per chunk.

Find the bug

Find the thread-unsafe line

Click the line that can give a wrong answer on a parallel stream.

Collect the even numbers in a list.

Round 1 of 4

Next step

Check your understanding

12 quick questions