Java Parallel Streams: When They Help, Ordering and Thread Safety
Use Java parallel streams correctly: parallelStream and parallel, why shared mutable state causes race conditions, encounter order and unordered(), groupingByConcurrent, when parallelism pays off, the common ForkJoinPool, running in a custom pool, and random numbers in parallel.
kvi5hnuCode Sprout team member10 min readOn this page
One of the selling points of streams is that switching from sequential to parallel processing is a single method call. The library splits the work across the processor cores, runs the pieces at the same time and assembles the results. It's mostly automatic, but not entirely. You have to follow a few rules, or you'll get wrong results, and parallelism doesn't always make things faster. This article covers both sides.
Getting a parallel stream
Any collection gives you a parallel stream with parallelStream(), and parallel() turns any stream into a parallel one:
Stream<String> parallelWords = words.parallelStream();
Stream<String> parallelWords = Stream.of(wordArray).parallel();
A stream pipeline is either entirely sequential or entirely parallel. You can't run some stages in parallel and others sequentially. What counts is the mode when the terminal operation runs, so with parallel() and sequential() the last call wins. isParallel() tells you which mode a stream is in.
Behind the scenes, parallel streams run on the common ForkJoinPool (Volume I, Part 10), which has about one thread per core, minus one, with the calling thread helping out. The stream's source is split recursively into chunks using its Spliterator, and the chunks are processed as fork-join tasks.
Rule one: no shared mutable state
A parallel stream must give the same result as a sequential one. That only works if the functions you pass in are stateless and don't interfere with each other or with the source. Here's what not to do. To count the short words by length, someone writes:
var shortWords = new int[12];
words.parallelStream().forEach(
s -> { if (s.length() < 12) shortWords[s.length()]++; }); // ERROR: race condition!
The lambda runs in several threads at once, all updating the same array. shortWords[n]++ reads, adds and writes back, and two threads can read the same old value, so increments get lost. That's the classic race condition from the concurrency chapters of Volume I. Run it a few times and you'll likely get different counts each time, all wrong. The demo leaves this code out because its output isn't predictable.
The cure is to stop sharing state and let the library combine results:
Map<Integer, Long> shortWordCounts = words.parallelStream()
.filter(s -> s.length() < 12)
.collect(groupingBy(String::length, counting()));
Each chunk counts into its own map, and the maps are merged at the end. If you truly need shared state, use a thread-safe structure designed for contention, such as LongAdder or ConcurrentHashMap. Usually, though, a reduction or collector is clearer and faster.
The same goes for the stream's source. Don't modify the collection while a stream over it is running, in parallel or not.
Ordering
Streams from lists, arrays, ranges and iterate, and the result of sorted, are ordered. (Stream.generate is the exception among the factory methods: its stream is unordered.) Results are assembled in the original order, so parallel results are entirely predictable: parallelStream().map(...).toList() gives the same list as the sequential version. Ordering doesn't prevent parallelism. For map, each chunk is processed independently and the pieces are put back together in order.
A few operations behave differently in parallel:
forEachvisits elements in whatever order threads get to them.forEachOrderedrespects encounter order, at the cost of some parallelism.findAnymay return any match.findFirstmust return the first one (article 5).
Dropping the order requirement
Some operations get cheaper when you don't care about order. Calling unordered() says so:
distinct()on an ordered stream must keep the first of equal elements. A thread processing a chunk can't know which duplicates to drop until all earlier chunks are done. Unordered, all chunks can use one shared set of seen elements.limit(n)on an ordered stream must return the firstnelements. If anynwill do,words.parallelStream().unordered().limit(n)can take whatever comes first.
Streams from a HashSet are unordered to begin with.
As article 10 explained, merging maps is expensive, so groupingByConcurrent fills one shared concurrent map instead. The values in each group are then not in stream order, which doesn't matter for an order-independent downstream collector such as counting().
When does parallel actually help?
Don't make every stream parallel in the hope of a speedup. Check these conditions:
- There's enough work. Splitting, scheduling tasks and merging results have a real cost. Parallelism pays off only for large data sets or expensive per-element work. For a few thousand cheap operations, it's usually slower. A rough rule of thumb: the number of elements times the cost per element should be well above 10,000 simple operations.
- The source splits well.
ArrayList, arrays andIntStream.rangesplit instantly into balanced halves.LinkedList,Stream.iterateandBufferedReader.lines()must be walked element by element and split badly. - The operations are CPU-bound. The common pool has only a few threads. If they block on file or network I/O, the whole pool, shared by every parallel stream in the JVM, sits idle. For blocking work, use virtual threads, for example with
Gatherers.mapConcurrent(article 14). - The merge is cheap. Combining lists or numbers is cheap. Merging big maps isn't.
- Boxing is avoided. Primitive streams (article 16) parallelize much better than
Stream<Integer>.
Measure before and after, ideally with a benchmarking tool such as JMH. Parallel streams work best with huge in-memory collections and computationally intensive processing.
Running in a custom pool
All parallel streams share the common pool. That's fine as long as your operations don't block and don't need to be isolated from other work. If you need a separate pool, there's a well-known trick: run the terminal operation from inside a task of your own ForkJoinPool. Stream tasks are then forked in that pool:
try (var pool = new ForkJoinPool(4)) {
result = pool.submit(() -> list.parallelStream().map(...).toList()).get();
}
This works only with a ForkJoinPool, not with other executors. It's a consequence of how fork-join works rather than a documented API guarantee, so use it sparingly. Since Java 19, ForkJoinPool is AutoCloseable, so try-with-resources shuts it down. The size of the common pool can be set at startup with the system property java.util.concurrent.ForkJoinPool.common.parallelism.
Random numbers in parallel
Sharing one java.util.Random among threads works, but all threads contend for its internal state. For streams of random numbers that will be processed in parallel, get a splittable generator, which can split itself into independent generators for each chunk:
var generator = RandomGenerator.SplittableGenerator.of("L64X128MixRandom");
double average = generator.doubles(100_000).parallel().average().orElseThrow();
Inside parallel lambdas, ThreadLocalRandom.current() is another good choice.
A complete example
import static java.util.stream.Collectors.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.random.*;
import java.util.stream.*;
public class Solution {
public static void main(String[] args) throws Exception {
List<String> words = new ArrayList<>();
String text = "it was the best of times it was the worst of times it was the age of wisdom "
+ "it was the age of foolishness it was the epoch of belief it was the epoch of incredulity";
for (int i = 0; i < 2000; i++) words.addAll(List.of(text.split(" ")));
System.out.println("words: " + words.size());
// getting a parallel stream; the last parallel()/sequential() call wins
System.out.println("parallelStream: " + words.parallelStream().isParallel());
System.out.println("parallel().sequential(): " + words.stream().parallel().map(String::length).sequential().isParallel());
// the safe way to count: group and count
Map<Integer, Long> counts = words.parallelStream().filter(s -> s.length() < 12)
.collect(groupingBy(String::length, TreeMap::new, counting()));
System.out.println("short word counts: " + counts);
Map<Integer, Long> sequentialCounts = words.stream().filter(s -> s.length() < 12)
.collect(groupingBy(String::length, TreeMap::new, counting()));
System.out.println("same as sequential: " + counts.equals(sequentialCounts));
// ordered streams give predictable results, even in parallel
List<String> upper = words.parallelStream().map(String::toUpperCase).limit(6).toList();
System.out.println("first six, uppercased in parallel: " + upper);
// forEach versus forEachOrdered
var ordered = new ArrayList<Integer>();
IntStream.range(0, 10).parallel().forEachOrdered(ordered::add);
System.out.println("forEachOrdered: " + ordered);
var unorderedVisits = new ConcurrentLinkedQueue<Integer>();
IntStream.range(0, 10).parallel().forEach(unorderedVisits::add);
System.out.println("forEach visited all ten (in some order): " + (unorderedVisits.size() == 10));
// dropping order: distinct and limit can do less work
Set<String> distinctWords = words.parallelStream().unordered().distinct().collect(toSet());
System.out.println("distinct words: " + distinctWords.size());
List<String> anyFive = words.parallelStream().unordered().limit(5).toList();
System.out.println("unordered limit(5) gave " + anyFive.size() + " words");
// groupingByConcurrent with an order-independent downstream collector
ConcurrentMap<Integer, Long> concurrentCounts = words.parallelStream()
.collect(groupingByConcurrent(String::length, counting()));
System.out.println("concurrent counts agree: " + new TreeMap<>(concurrentCounts).equals(
words.stream().collect(groupingBy(String::length, TreeMap::new, counting()))));
// a thread-safe accumulation when you really need shared state
var lengthTotal = new LongAdder();
words.parallelStream().forEach(w -> lengthTotal.add(w.length()));
System.out.println("LongAdder total: " + lengthTotal.sum() + ", mapToInt sum: "
+ words.parallelStream().mapToInt(String::length).sum());
// running a parallel stream in a custom ForkJoinPool
try (var pool = new ForkJoinPool(2)) {
Set<Boolean> inPool = pool.submit(() -> IntStream.range(0, 1000).parallel()
.mapToObj(_ -> Thread.currentThread() instanceof ForkJoinWorkerThread t && t.getPool() == pool)
.collect(toSet())).get();
System.out.println("all work ran in the custom pool: " + inPool);
}
// random numbers for parallel streams
var generator = RandomGenerator.SplittableGenerator.of("L64X128MixRandom");
double average = generator.doubles(100_000).parallel().average().orElseThrow();
System.out.println("average of 100,000 random doubles is close to 0.5: " + (Math.abs(average - 0.5) < 0.01));
System.out.println("common pool parallelism > 0: " + (ForkJoinPool.getCommonPoolParallelism() > 0));
}
}
words: 72000
parallelStream: true
parallel().sequential(): false
short word counts: {2=24000, 3=28000, 4=2000, 5=10000, 6=4000, 11=4000}
same as sequential: true
first six, uppercased in parallel: [IT, WAS, THE, BEST, OF, TIMES]
forEachOrdered: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
forEach visited all ten (in some order): true
distinct words: 13
unordered limit(5) gave 5 words
concurrent counts agree: true
LongAdder total: 258000, mapToInt sum: 258000
all work ran in the custom pool: [true]
average of 100,000 random doubles is close to 0.5: true
common pool parallelism > 0: true
The demo repeats a sentence many times to get a word list. Everything printed is independent of the number of cores, so the output is the same on any machine.
Common questions
How many threads does a parallel stream use?
The common pool has Runtime.getRuntime().availableProcessors() - 1 worker threads, and the thread that calls the terminal operation joins in, so the stream uses about one thread per core. Containers matter here: inside a Docker container with a CPU limit, the JVM sees the limit, not the host's cores.
Do parallel streams use virtual threads?
No. They run on the platform threads of the fork-join pool, because they are meant for CPU-bound work. For many blocking tasks, use virtual threads, for example through Gatherers.mapConcurrent or Executors.newVirtualThreadPerTaskExecutor().
Should I use parallel streams inside a web server? Usually not for request handling. A server already runs many requests at once, so the cores are busy anyway. And all parallel streams share one common pool, so a few large requests can slow down every other request that uses a parallel stream. Parallel streams suit batch jobs, data processing and CPU-heavy computations that run on their own.
Can I call a database or a REST service in a parallel stream?
It works, but it is a poor fit: those calls block, and while they wait they hold a thread of the small shared pool. Use mapConcurrent or an executor with virtual threads, and limit concurrency to what the database or service can handle.
My parallel stream is slower than the sequential one. Why?
Typical causes are too little work per element, a source that splits badly (LinkedList, iterate, lines from a reader), boxing, an expensive merge step (such as maps), ordered limit/distinct/findFirst, or synchronization in the lambdas. Measure with JMH after warm-up; a single timing with System.nanoTime is misleading because of JIT compilation.
Is parallelStream().collect(toList()) thread-safe?
Yes. Collectors give each chunk its own container and merge them safely; you never need a synchronized list for that. Only your own shared state inside lambdas is unsafe.
API reference
java.util.stream.BaseStream<T, S>
| Method | Description |
|---|---|
S parallel() | a parallel stream with the same elements |
S sequential() | a sequential stream with the same elements |
boolean isParallel() | whether the terminal operation would run in parallel |
S unordered() | a stream that need not preserve encounter order |
java.util.Collection<E>
| Method | Description |
|---|---|
Stream<E> parallelStream() | a possibly parallel stream of the collection's elements |
java.util.concurrent.ForkJoinPool
| Method | Description |
|---|---|
static ForkJoinPool commonPool() | the shared pool used by parallel streams |
static int getCommonPoolParallelism() | the target parallelism of the common pool |
ForkJoinPool(int parallelism) | a new pool with the given parallelism |
java.util.random.RandomGenerator.SplittableGenerator (Java 17)
| Method | Description |
|---|---|
static SplittableGenerator of(String name) | a splittable generator of the named algorithm, such as "L64X128MixRandom" |
Summary
parallelStream()orparallel()makes a pipeline parallel. The mode at the terminal operation applies to the whole pipeline.- Functions passed to parallel streams must be stateless and must not modify shared data or the source. Use collectors and reductions instead of mutating shared variables.
- Ordered streams give predictable results in parallel.
unordered()can speed updistinctandlimit, andgroupingByConcurrentavoids map merging. - Parallelism pays off for large, well-splittable, CPU-bound workloads. Blocking operations starve the shared common pool.
- A custom
ForkJoinPoolcan host a parallel stream. Use splittable or thread-local generators for random numbers.
Practice Questions
What's wrong with words.parallelStream().forEach(w -> result.add(w.toUpperCase())) where result is an ArrayList?
Several threads call add on the same non-thread-safe ArrayList at once, which can lose elements, throw ArrayIndexOutOfBoundsException or corrupt the list. Even if it worked, the order would be random. Use words.parallelStream().map(String::toUpperCase).toList().
Is stream.parallel().filter(...).sequential().map(...).toList() partly parallel?
No. A pipeline runs entirely in one mode, determined by the last parallel() or sequential() call before the terminal operation. This one runs sequentially.
Does list.parallelStream().map(f).toList() return elements in the original order?
Yes. A list stream is ordered, so the results are reassembled in encounter order, even though f is applied to chunks concurrently.
Why might parallelizing the sum of a 1,000-element Stream<Integer> make it slower?
The work is tiny compared with the overhead of splitting, scheduling fork-join tasks and combining results, and boxing makes each step more expensive. Parallelism pays off only for large inputs or costly per-element work, ideally with primitive streams.
Your parallel stream calls a slow web service for each element, and other parts of the application slow down. Why?
Parallel streams share the common ForkJoinPool, which has only about as many threads as cores. Blocking calls tie up those threads, starving every other parallel stream and fork-join task in the JVM. Use Gatherers.mapConcurrent or an executor with virtual threads for blocking I/O.
Previous: Java Primitive Streams: IntStream, LongStream and DoubleStream
Related reading
- Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
- Java Primitive Streams: IntStream, LongStream and DoubleStream
- Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism
- Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect
- Implementing Custom Java Collectors with Collector.of

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.