Lesson · Stream API
Parallel streams: what actually changes
13 min readParallel Streams & Execution
parallel() splits the source into chunks, runs the pipeline on several threads, and combines the answers. It is a one-word change with real preconditions: independent data, associative operations, and enough work to pay for the split.
How the work is split
Calling parallel() marks the pipeline as splittable. When the terminal operation starts, the framework splits the source (a list, range or array) into chunks and hands them to the ForkJoinPool common pool. Each chunk runs the full pipeline, then partial results are merged: sums added, minimums compared, collector containers combined.
That design explains the requirements. Splitting needs a splittable, independent source; merging needs an associative operation; and the merge stage is why collect with a collector is parallel-safe while populating a shared ArrayList is not.
IntStream.rangeClosed(1, 1_000_000).parallel() // split into chunks .map(i -> i * 2) // runs per chunk .sum(); // partial sums merged
Parallel pipeline · 8 elements over 2 workers
source
The source is an independent, splittable sequence. Nothing has run yet: parallel() only marked the pipeline as splittable.
When it helps and when it hurts
Parallelism pays when there is a lot of genuinely independent CPU work per element. It loses money for small streams (split and merge overhead exceeds the work), for IO-bound work (blocking threads do not get faster), and for stateful or order-sensitive pipelines (synchronization eats the gain).
A reasonable default: start sequential, measure if it matters, and only parallelize after a measurement shows the win. Guessing wrong is common in both directions.
- Good fit: big numeric folds, CPU-heavy per-element computation, independent transformations.
- Bad fit: small data, IO inside the pipeline, anything using shared mutable state.
- Unsafe: operations that are not associative (subtraction, string concatenation order, non-commutative reductions).
Shared mutable state is the classic failure
Adding elements to a plain ArrayList from forEach in a parallel pipeline is a data race: two threads resize the same backing array and elements are lost, duplicated or the run crashes. The result is not just 'slightly wrong', it can differ on every execution.
The idiomatic fix is not synchronization, it is collect: the collector gives each chunk its own container and merges at the end, so no state is shared. Same for reduce with an associative function: partial results are combined structurally.
// race: shared ArrayList across threads IntStream.range(0, 1000).parallel().forEach(sharedList::add); // wrong, loses elements // correct: per-chunk containers, merged by the collector IntStream.range(0, 1000).parallel().boxed().collect(Collectors.toList());
Order, findFirst and findAny
Encounter order is not given up by parallel() itself: collect(toList) still produces elements in source order, and forEachOrdered guarantees ordered output at the cost of coordination. Plain forEach in a parallel stream makes no order promise at all.
findAny exists precisely for parallel: it may return whichever matching element a worker finds first, no ordering work required, whereas findFirst must respect encounter order and can give up parallel speed to do it.
Switching back and reading the pool
sequential() marks the pipeline sequential again, and the last call between parallel() and sequential() wins. One less-visible consequence: calling parallel() on a stream you received (a parameter, a field) mutates its mode for whoever else might use it, so decide mode at the point the stream is created.
Behind the scenes is ForkJoinPool.commonPool(), whose parallelism defaults to available processors minus one. All parallel streams in the JVM share it, which is why one hot pipeline can starve another.
parallel() is a request, not a promise of speed. The mechanics are identical in both modes; only the splitting and merging differ, and that is exactly where the cost and the correctness requirements live.
The three questions before parallel()
Is there enough work? Is the operation associative? Is any state shared? Three no doubts, parallelize; any hesitation, stay sequential. A parallel pipeline that is wrong is much worse than one that is twice as slow.
Interview angles
What does parallel() actually do to the pipeline?+
It marks the stream as splittable. At terminal time the source is split into chunks, chunks run on ForkJoinPool threads, and partial results are merged with the operation's combiner or an associative fold.
Why is collect safe in parallel but forEach with a shared list is not?+
A collector builds one container per chunk and merges them at the end, so no thread touches another's state. A shared list written from parallel forEach is a data race with lost updates and possible crashes.
When should parallel streams not be used?+
Small data, IO-bound work, stateful pipelines, order-sensitive logic without forEachOrdered, and non-associative reductions. In all of those the split and merge cost is real and the speedup is not.
Difference between findFirst and findAny?+
findFirst honors encounter order and may sacrifice parallel speed. findAny may return any matching element and is the parallel-friendly choice when any match will do.
What happens with a non-associative reduction in parallel?+
Results can differ from the sequential run, because partial results are merged in an order the framework chooses. Subtraction is the classic example: the chunking changes the answer.