Thread-Safe Maps and Stream Collectors in Java
BehavioralModel answerLast updated
Compare Java's concurrent map implementations and write a Stream-based method to find the highest-value transaction per trader.
Part 1: Thread-Safe Map Implementations
Compare two approaches to thread-safe maps in Java: ConcurrentHashMap and wrapping a HashMap with Collections.synchronizedMap(). Your answer should cover:
- How each approach implements synchronization and what this means for concurrent access patterns
- The behavior of their iterators when the map is modified during iteration
- Trade-offs in performance and safety
Part 2: Finding Maximum Transactions with Streams
Given a list of Transaction objects where each has:
String traderId— identifier for the traderint amount— transaction valueString currency— currency code
Implement a method using Java Streams that produces a Map<String, Optional<Transaction>>. The map should associate each trader ID with an Optional holding their highest-amount transaction.
class Transaction {
String traderId;
int amount;
String currency;
// Constructor and getters provided
}
Requirements:
- Use
Collectors.groupingByfor partitioning by trader - Use
Collectors.maxByto identify the largest transaction - Handle empty inputs without errors
Sample Input:
[Transaction("trader1", 150, "USD"),
Transaction("trader1", 300, "USD"),
Transaction("trader2", 75, "EUR")]
Expected Output:
{"trader1": Optional[Transaction("trader1", 300, "USD")],
"trader2": Optional[Transaction("trader2", 75, "EUR")]}
Hints
Hint 1
For Part 1: think about whether locks are per-map or per-bucket, and whether iteration requires external locking
Hint 2
For Part 2: the downstream collector in groupingBy will run separately for each trader's transactions
Hint 3
Consider what happens with null values in both the concurrent map and the stream pipeline
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part 1: Thread-Safe Map Comparison
Synchronization Strategy
Collections.synchronizedMap(new HashMap()) wraps each method in a synchronized block using a single mutex. Every operation—get, put, remove, size—acquires this shared lock. This means:
- All operations serialize through one bottleneck
- Readers contend with other readers and writers
- Compound operations like check-then-put require manual external synchronization
- The underlying
HashMappermits null keys and values
ConcurrentHashMap uses fine-grained locking optimized for concurrent throughput:
- Read operations proceed without locks using volatile memory semantics
- Writes to empty buckets use compare-and-swap (CAS) with no locking
- Updates to populated buckets lock only that specific bucket's head node
- Since Java 8, buckets convert to tree structures when they exceed a threshold, maintaining O(log n) worst-case performance
- Built-in atomic operations:
putIfAbsent,computeIfAbsent,compute,merge - Does not allow null keys or values (null would be ambiguous with "absent")
The practical difference: ConcurrentHashMap allows many concurrent readers and writers to operate on different buckets simultaneously. A synchronizedMap forces all operations into a queue.
Iterator Behavior
synchronizedMap has fail-fast iterators. The underlying HashMap iterator tracks a modification count. If the map changes structurally during iteration (except via the iterator's own remove method), it throws ConcurrentModificationException. Critically, you must hold the map's lock for the entire iteration:
synchronized (syncMap) {
for (Map.Entry<K, V> entry : syncMap.entrySet()) {
// process entry
}
}
Without this external synchronization, the iterator is unsafe even though individual get/put calls are synchronized. The fail-fast check is best-effort—it may miss concurrent modifications.
ConcurrentHashMap provides weakly consistent iterators. These iterators:
- Never throw
ConcurrentModificationException - Reflect elements present at iterator creation time
- May or may not reflect subsequent modifications
- Guarantee each element appears at most once
- Require no external locking
"Weakly consistent" does not mean snapshot. The iterator sees some state from creation time onward but makes no promises about changes after creation. For a true point-in-time snapshot, you would need to copy the map.
Performance Trade-offs
ConcurrentHashMap dominates for high-concurrency workloads. With multiple threads, its lock-free reads and bucket-level write locks provide orders of magnitude better throughput. synchronizedMap remains useful when:
- You need null keys or values
- The map is accessed by only one or two threads
- You're wrapping a specialized
Mapimplementation with no concurrent equivalent
Part 2: Stream-Based Transaction Aggregation
Approach
The Stream API's groupingBy collector partitions elements by key, applying a downstream collector to each partition. We group transactions by trader ID, then apply maxBy as the downstream collector. Since maxBy returns an Optional (empty if the group is empty), the result type is naturally Map<String, Optional<Transaction>>.
In practice, each trader ID group contains at least one transaction, so the Optional values are never empty. Traders with no transactions simply don't appear in the map.
Implementation
import java.util.*;
import java.util.stream.Collectors;
public class TransactionAnalyzer {
public static Map<String, Optional<Transaction>>
findMaxTransactionPerTrader(List<Transaction> transactions) {
if (transactions == null || transactions.isEmpty()) {
return Collections.emptyMap();
}
return transactions.stream()
.filter(Objects::nonNull)
.filter(t -> t.getTraderId() != null)
.collect(Collectors.groupingBy(
Transaction::getTraderId,
Collectors.maxBy(
Comparator.comparingInt(Transaction::getAmount))));
}
}
How It Works
-
Null filtering:
groupingBythrowsNullPointerExceptionif any element maps to a null key. We filter out null transactions and null trader IDs to prevent this. -
Grouping:
groupingBy(Transaction::getTraderId, ...)creates a separate collector instance for each trader ID, routing transactions to the corresponding collector. -
Finding maximum:
maxBy(Comparator.comparingInt(Transaction::getAmount))reduces each trader's transactions using a comparator on amount. It returns the transaction with the highest amount for that trader. -
Result type:
maxByproducesOptional<Transaction>(to handle potentially empty groups). SincegroupingByonly creates keys for traders who have transactions, allOptionalvalues are present in this case.
Complexity
- Time: O(n) where n is the number of transactions. One pass through the stream with constant-time hash operations.
- Space: O(k) where k is the number of distinct traders. Each group stores only the current maximum, not all transactions.
Edge Cases
- Empty or null input: Returns an empty map immediately.
- Null transactions or trader IDs: Filtered out before grouping.
- Equal amounts: When multiple transactions have the same amount for a trader, the first encountered wins. For deterministic tie-breaking, chain comparators:
comparingInt(Transaction::getAmount).thenComparing(Transaction::getCurrency). - Currency differences: The comparison uses raw amounts regardless of currency. In production, you would likely convert to a common currency first or ask for clarification.
Alternative Formulations
Since groups are never empty, you could simplify to Map<String, Transaction>:
.collect(Collectors.toMap(
Transaction::getTraderId,
t -> t,
BinaryOperator.maxBy(Comparator.comparingInt(Transaction::getAmount))))
Or unwrap the Optional explicitly:
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(
Transaction::getTraderId,
Collectors.maxBy(Comparator.comparingInt(Transaction::getAmount))),
map -> map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().get()))))
The original formulation matches the specification exactly, but mentioning these alternatives demonstrates deeper understanding of the collector API.
Common Mistakes
- Forgetting to handle null inputs, causing
NullPointerException - Trying to use
max()directly (which returnsOptional<Transaction>for the entire stream, not per trader) - Using
Collectors.reducinginstead ofmaxBy(works but is more verbose) - Not filtering null trader IDs before grouping