00:00

Thread Safety in Java Parallel Streams

Last updated:

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

PatternSafe in parallel?Why
collect(Collectors.toList()), toList()YesEach thread fills its own container; containers are merged
reduce() with an associative function and true identityYesPartial results are combined
forEach(list::add) on an ArrayListNoConcurrent writes corrupt the list
forEach(x -> counter++) on a field or arrayNoLost updates
forEach(map::merge) on a HashMapNoCorrupted map
forEach(set::add) on ConcurrentHashMap.newKeySet()Yes, but slowerThread-safe collection, with contention
AtomicLong.incrementAndGet()Yes, but slowerAtomic operation, with contention
groupingByConcurrent()YesDesigned 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.

A lost update on a shared counter Two threads read the shared counter value 41 at the same time. Each adds 1 and writes 42. The counter ends at 42 although two increments happened, so one update was lost. THREAD A THREAD B 1. read read 41 read 41 2. add 1 compute 42 compute 42 3. write write 42 write 42 Result counter = 42, expected 43
Figure 1: 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().

UnsafeListVsCollect.java
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");
    }
}
Output
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().

CounterRace.java
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);
    }
}
Output
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().

ConcurrentGrouping.java
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));
    }
}
Output
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.

StatelessParallel.java
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));
    }
}
Output
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 ConcurrentHashMap is 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 (synchronized blocks) 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

GoalUnsafeSafe
Build a listforEach(list::add)toList() / collect()
Countcounter++count()
Sumtotal += xmapToLong(...).sum()
GroupforEach(m -> map.merge(...)) on HashMapgroupingBy() / groupingByConcurrent()
Distinct setforEach(set::add) on HashSetcollect(toSet()) or distinct()

7. Common Mistakes and Best Practices

Using synchronizedList as a fix

Works, but poorly
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

Risky
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 SimpleDateFormat or Random in parallel lambdas; use DateTimeFormatter and ThreadLocalRandom.
  • 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() and sum() 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