Parallel streams
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · Same answer, sequential or parallel
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()); }}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 bysequential()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
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())); }}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
mainand theForkJoinPool.commonPool-workerthreads. Run it twice and the order changes. - The pool size is the number of cores minus one; the
mainthread 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.
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
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)); }}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
forEachOrderedandtoList()follow the encounter order even in parallel, so this output is the same on every run.findFirstis always 35, the first failing mark in the list.findAnymay 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
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)); }}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
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); }}AtomicLong total: 7485000
sum() total: 7485000
Per bank: {HDFC=2495000, ICICI=2495000, SBI=2495000}What this code does
- An
AtomicLongis 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()andgroupingBygive 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
seenset or a running total. - No shared changes: never change an outside list, map, field or counter. Let
toList,sum,countand 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 cmust equala 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 4Next step
Check your understanding
12 quick questions