Thread Safety in Java Parallel Streams
Thread safety in parallel streams is about what happens when the lambdas of a parallel pipeline, which run on several threads at once, touch shared state. The Stream API (Java 8+) itself is safe: each worker processes its own part, and collectors combine results without shared mutable containers. Problems appear only when your code adds shared mutable state, such as an outside ArrayList or a counter.
This tutorial shows typical race conditions, why they happen, and the safe patterns: collectors, reductions, concurrent collections and atomic variables.
1. Safe and Unsafe Patterns
| Pattern | Safe in parallel? | Why |
|---|---|---|
collect(Collectors.toList()), toList() | Yes | Each thread fills its own container; containers are merged |
reduce() with an associative function and true identity | Yes | Partial results are combined |
forEach(list::add) on an ArrayList | No | Concurrent writes corrupt the list |
forEach(x -> counter++) on a field or array | No | Lost updates |
forEach(map::merge) on a HashMap | No | Corrupted map |
forEach(set::add) on ConcurrentHashMap.newKeySet() | Yes, but slower | Thread-safe collection, with contention |
AtomicLong.incrementAndGet() | Yes, but slower | Atomic operation, with contention |
groupingByConcurrent() | Yes | Designed for concurrent accumulation |
2. Why Shared State Breaks
A parallel stream runs your lambdas on several worker threads. If a lambda only reads its argument and returns a value, the threads never interfere. If it writes to an object shared across threads, the threads can interleave their reads and writes, so updates get lost or internal structures, such as an ArrayList's backing array, become inconsistent.
The safe approach is to make lambdas stateless and let the stream combine results: collect(), reduce(), sum() and count() are designed for parallel execution. Thread-safe collections and atomic variables also work, but they make threads compete for the same memory, which reduces the parallel speed-up.
counter++ is a read, an add and a write. When two threads interleave these steps, one increment overwrites the other.3. Java Examples
Example 1: An unsafe ArrayList compared with collect()
Gather the even numbers up to 200,000 with forEach() into an ArrayList, and with collect().
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class UnsafeListVsCollect {
public static void main(String[] args) {
List<Integer> unsafe = new ArrayList<>();
try {
IntStream.rangeClosed(1, 200_000).parallel().filter(n -> n % 2 == 0).forEach(unsafe::add);
System.out.println("forEach into ArrayList: " + unsafe.size() + " elements (expected 100000)");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("forEach into ArrayList: ArrayIndexOutOfBoundsException");
}
List<Integer> safe = IntStream.rangeClosed(1, 200_000).parallel()
.filter(n -> n % 2 == 0).boxed().collect(Collectors.toList());
System.out.println("collect(): " + safe.size() + " elements");
}
}
forEach into ArrayList: 21345 elements (expected 100000) collect(): 100000 elements
The first line varies: the size is usually below 100000, and sometimes the program reports an exception instead. The second line is always 100000.
How it works: Concurrent add() calls overwrite each other or overflow the backing array, so elements go missing or an exception is thrown. collect() gives each thread its own list and merges them, so the count is always right.
Example 2: A shared counter compared with count() and AtomicLong
Count multiples of 3 in a range with an unsafe counter, an AtomicLong and count().
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
public class CounterRace {
public static void main(String[] args) {
long[] plain = {0};
AtomicLong atomic = new AtomicLong();
IntStream.range(0, 3_000_000).parallel().filter(n -> n % 3 == 0).forEach(n -> plain[0]++);
IntStream.range(0, 3_000_000).parallel().filter(n -> n % 3 == 0).forEach(n -> atomic.incrementAndGet());
long counted = IntStream.range(0, 3_000_000).parallel().filter(n -> n % 3 == 0).count();
System.out.println("plain counter: " + plain[0] + (plain[0] == 1_000_000 ? "" : " (lost updates)"));
System.out.println("AtomicLong: " + atomic.get());
System.out.println("count(): " + counted);
}
}
plain counter: 206460 (lost updates) AtomicLong: 1000000 count(): 1000000
The plain counter's value changes from run to run; the other two lines are always 1000000.
How it works: The plain counter loses most of its increments. AtomicLong is correct but makes every thread contend for one variable. count() is correct, simplest and fastest.
Example 3: Thread-safe grouping (Java 9+)
Count words by first letter in parallel, with groupingByConcurrent() and with groupingBy().
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
public class ConcurrentGrouping {
public static void main(String[] args) {
List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry", "apricot", "beet");
ConcurrentMap<Character, Long> concurrent = words.parallelStream()
.collect(Collectors.groupingByConcurrent(w -> w.charAt(0), Collectors.counting()));
Map<Character, Long> merged = words.parallelStream()
.collect(Collectors.groupingBy(w -> w.charAt(0), Collectors.counting()));
System.out.println("groupingByConcurrent: " + new TreeMap<>(concurrent));
System.out.println("groupingBy: " + new TreeMap<>(merged));
}
}
groupingByConcurrent: {a=3, b=3, c=1}
groupingBy: {a=3, b=3, c=1}
How it works: Both are correct. groupingBy() builds a map per thread and merges them; groupingByConcurrent() accumulates into one shared ConcurrentMap, which avoids merging but does not preserve encounter order within groups.
Example 4: Stateless lambdas with immutable results (Java 16+)
Compute a 10% discount for every price in parallel without any shared state.
import java.util.List;
import java.util.stream.IntStream;
public class StatelessParallel {
record Price(String sku, int paise) { }
public static void main(String[] args) {
List<Price> prices = IntStream.rangeClosed(1, 6)
.mapToObj(i -> new Price("SKU-" + i, i * 10_000))
.toList();
List<Price> discounted = prices.parallelStream()
.map(p -> new Price(p.sku(), p.paise() * 9 / 10)) // new object, nothing shared
.toList();
System.out.println(discounted.get(0) + " ... " + discounted.get(5));
System.out.println("Original unchanged: " + prices.get(0));
}
}
Price[sku=SKU-1, paise=9000] ... Price[sku=SKU-6, paise=54000] Original unchanged: Price[sku=SKU-1, paise=10000]
How it works: Each lambda creates a new immutable record from its input. No thread ever writes to shared state, so the code is safe in any mode, and toList() keeps encounter order.
4. Real-World Use Cases
- Reviewing code: any
forEach()that writes to an outside variable is a red flag in parallel code. - Aggregations: totals, counts and groupings with collectors rather than shared maps.
- Caches: a
ConcurrentHashMapis acceptable when parallel tasks must share lookups.
5. Important Points
- Stateless lambdas are the goal: output depends only on input.
- Non-interference: never modify the stream's source during the pipeline.
- Thread-safe collections avoid corruption but add contention.
- Synchronisation inside lambdas (
synchronizedblocks) serialises the work and can cause deadlocks. - Mutable elements: changing fields of shared objects in parallel is just as unsafe as writing to a list.
6. Unsafe vs Safe Alternatives
| Goal | Unsafe | Safe |
|---|---|---|
| Build a list | forEach(list::add) | toList() / collect() |
| Count | counter++ | count() |
| Sum | total += x | mapToLong(...).sum() |
| Group | forEach(m -> map.merge(...)) on HashMap | groupingBy() / groupingByConcurrent() |
| Distinct set | forEach(set::add) on HashSet | collect(toSet()) or distinct() |
7. Common Mistakes and Best Practices
Using synchronizedList as a fix
List<Integer> result = Collections.synchronizedList(new ArrayList<>());
numbers.parallelStream().forEach(result::add); // correct size, but order is random and threads queue on one lock
A synchronized list stops corruption, but threads now wait for one lock and the order is lost. toList() is correct, ordered and faster.
Mutating elements in parallel
orders.parallelStream().forEach(o -> o.setStatus("PROCESSED")); // races if objects are shared elsewhere
Produce new objects with map(), or make sure each element is touched by exactly one thread and not read elsewhere concurrently.
Other mistakes to avoid
- Reading a shared variable that another lambda writes.
- Using a non-thread-safe
SimpleDateFormatorRandomin parallel lambdas; useDateTimeFormatterandThreadLocalRandom. - Assuming the source collection is safe to modify concurrently.
8. Summary
- Parallel stream lambdas run on several threads; shared mutable state causes races.
- Collectors, reductions,
count()andsum()are designed for parallel use. - Concurrent collections and atomics are correct but add contention.
- Keep lambdas stateless and create new objects instead of mutating shared ones.
9. References
Frequently Asked Questions (FAQ)
Q1. Are Java parallel streams thread-safe?
The Stream API's own operations are safe to use in parallel. Your lambdas are not automatically safe: if they modify shared mutable state, such as an outside ArrayList or counter, you get race conditions.
Q2. Why does adding to an ArrayList from a parallel stream lose elements?
ArrayList is not thread-safe. Concurrent add() calls can overwrite each other's slots or resize the backing array at the same time, so elements are lost or ArrayIndexOutOfBoundsException is thrown.
Q3. What is the safe way to build a list in a parallel stream?
Use toList() or collect(Collectors.toList()). Each worker thread fills its own list, and the lists are merged in encounter order.
Q4. Should I use AtomicInteger or ConcurrentHashMap in parallel streams?
They are correct but make threads contend for shared memory, which reduces the speed-up. Prefer count(), sum(), reduce() and collectors whenever they can express the result.
Q5. What does stateless lambda mean?
A stateless lambda's result depends only on its input and it changes nothing outside itself. Such lambdas are safe in parallel streams.