ConcurrentHashMap & Concurrent Collections
Use purpose-built concurrent collections instead of manual locking around HashMap/List.
📌 Key Idea
HashMap is unsafe for concurrent mutation. Prefer ConcurrentHashMap, ConcurrentLinkedQueue, CopyOnWriteArrayList, or blocking queues based on read/write profile.Why It Matters
- Concurrent writes on plain
HashMapcan cause races and corrupted state. ConcurrentHashMapuses fine-grained/CAS-based concurrency, so throughput is far better than one global lock in many workloads.- Concurrent maps/queues give thread-safe access patterns without forcing a single global lock around every operation.
When to Use
- Shared mutable maps/queues accessed by many threads.
- High-throughput caches/counters/registries.
- Need weakly-consistent iteration under concurrent updates.
When NOT to Use
- Single-thread confined state.
- CopyOnWrite structures under heavy writes (expensive copies).
Code Variations
1?? Atomic map update without external lockjava
ConcurrentHashMap<String, LongAdder> counts = new ConcurrentHashMap<>();
counts.computeIfAbsent(key, k -> new LongAdder()).increment();Avoids race from get+put pattern.
2?? Unsafe pattern to avoidjava
Map<String, Integer> m = new HashMap<>();
// two threads mutate/read m concurrently -> undefined behaviorWrap with synchronization or replace with concurrent collection.
Collection choice quick guide
| Aspect | Type | Best for | Watch-out |
|---|---|---|---|
| ConcurrentHashMap | Read/write maps, high concurrency | No null keys/values | |
| CopyOnWriteArrayList | Many reads, rare writes | Writes are O(n) copy | |
| ConcurrentLinkedQueue | Non-blocking producer/consumer | No built-in backpressure | |
| BlockingQueue | Backpressure + producer/consumer | Threads block on put/take |
Interview Q&A
Quick Cheat Sheet
Default mapConcurrentHashMap for shared mutable key-value state.
Counter patternConcurrentHashMap + LongAdder.
AvoidRaw HashMap under concurrent writes.