Thread-Safe Collectors in Parallel Streams
A financial application processes millions of transactions daily. The original code uses a for loop to aggregate transactions into a Map<Long, TransactionSummary> where the key is account ID. To improve performance, a developer refactors it using parallel streams: transactions.parallelStream() .collect(Collectors.toMap( Transaction::getAccountId, Function.identity(), (t1, t2) -> t1.merge(t2), // merging logic HashMap::new )); After deployment, they observe that the resulting map is smaller than expected and some transaction summaries are missing. Profiling shows the merge function is called infrequently, suggesting that the map is losing entries. What is the most likely cause and the correct fix?
Quick Answer
The answer is to replace `HashMap::new` with `ConcurrentHashMap::new` in the collector. This is correct because `Collectors.toMap` with a `HashMap` supplier is not thread-safe; when used with a parallel stream, multiple threads concurrently write to the same map, causing race conditions that silently drop entries and produce a smaller map than expected. The merge function is actually associative and correct, so the real issue is the non-concurrent map supplier, which violates the thread safety required for parallel reduction. On the Oracle Certified Professional Java SE 17 Developer 1Z0-829 exam, this question tests your understanding of parallel streams collector thread safety and the critical distinction between concurrent and non-concurrent collectors. A common trap is assuming the merge function is the culprit, but the exam expects you to recognize that the map supplier must be thread-safe for parallel accumulation. Memory tip: “Parallel streams need concurrent collections—if your map is missing entries, check the supplier, not the merger.”
⚠ Common exam trap
Oracle often tests the misconception that the merge function must be associative when the real culprit is the thread-unsafe map supplier in parallel stream collectors.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
Replace HashMap::new with ConcurrentHashMap::new in the collector.
The issue is that `HashMap::new` is not thread-safe. When `parallelStream()` splits the stream into multiple threads, each thread creates its own `HashMap` for partial results. These partial maps are then merged using the collector's combiner, but `HashMap` does not guarantee thread safety during concurrent access or merging. Using `ConcurrentHashMap::new` ensures that the map can be safely populated and combined across threads, preventing lost entries. The merge function itself is associative (merging two summaries into one), so the problem is purely the thread-unsafe map supplier.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
Remove parallelStream() and use sequential stream to avoid concurrency issues.
Why it's wrong here
While this would work, it sacrifices the parallelism benefit. The goal is to maintain performance while fixing correctness.
- ✗
The merge function is not associative; change it to use a combiner that is associative.
Why it's wrong here
The merge function appears associative as it combines two summaries. The issue is not associativity.
- ✗
Use forEach with a ConcurrentHashMap and putIfAbsent to manually merge.
Why it's wrong here
This approach is error-prone and may still cause race conditions. The collect method with proper collector is preferred.
- ✓
Replace HashMap::new with ConcurrentHashMap::new in the collector.
Why this is correct
In parallel streams, the default toMap collector uses HashMap which is not thread-safe. ConcurrentHashMap allows safe concurrent insertion and merging.
Go deeper
Related to this question
About these practice questions
Courseiva writes every 1Z0-829 question from scratch — 513 in total, each with an explanation and a wrong-answer breakdown. None are copied from real exams or dumps. Learn why practice questions differ from exam dumps →
Same concept, more angles
1 more way this is tested on 1Z0-829
These questions test the same concept from different angles. Work through them to make sure you can recognise it however the exam phrases it.
Variation 1. A company runs a financial application that processes a stream of millions of transaction records daily. Each record is a 'Transaction' object with fields: id, amount, currency, timestamp. The system currently uses a parallel stream to group transactions by currency and compute the sum of amounts per currency, using the following code: Map<String, Double> result = transactions.parallelStream() .collect(Collectors.groupingBy(Transaction::getCurrency, Collectors.summingDouble(Transaction::getAmount))); Recently, performance has degraded significantly. Analysis shows that the stream source is a LinkedList, and the operation involves a large number of distinct currencies (over 1000). The JVM is running on a machine with 4 cores. Which is the best course of action to improve performance?
hard- A.Change the stream source to an ArrayList and use sequential stream.
- B.Use a custom thread pool with ForkJoinPool to control parallelism.
- C.Increase the parallelism level to 8.
- ✓ D.Replace groupingBy with a custom concurrent collector using ConcurrentHashMap.
Why D: The performance degradation stems from the parallel stream using a shared `ConcurrentHashMap` internally for the `groupingBy` collector, which incurs significant overhead when merging partial results from many threads, especially with over 1000 distinct currencies. A custom concurrent collector using `ConcurrentHashMap` directly eliminates this merge overhead by allowing threads to update the map concurrently without synchronization bottlenecks, improving throughput on a 4-core machine.
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This 1Z0-829 practice question is part of Courseiva's free Oracle certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the 1Z0-829 exam.