ConcurrentHashMap and Thread-Safe Collections
ConcurrentHashMap is the go-to map for shared state between threads. Interviewers ask how it stays thread-safe without locking the whole map, how it differs from Collections.synchronizedMap, and how to update values atomically.
What you will learn
- Explain how ConcurrentHashMap achieves concurrency
- Use compute, merge and putIfAbsent for atomic updates
- Compare synchronized wrappers and concurrent collections
- Know CopyOnWriteArrayList and BlockingQueue
Key concepts
Java 8+ design
No segments any more. Reads are lock-free with volatile reads. A write to an empty bin uses CAS; a write to a non-empty bin locks only that bin's first node. Resizing is shared between threads.
Atomic compound operations
map.get then map.put is two steps and races. Use merge, compute, computeIfAbsent or putIfAbsent, which run atomically per key.
synchronizedMap
Wraps every method in one lock, so threads queue up. Iteration still needs manual synchronization.
Other concurrent collections
CopyOnWriteArrayList (copies on write, great for many reads and rare writes such as listener lists), ConcurrentLinkedQueue, and BlockingQueue implementations for producer-consumer.
Step by step
Counting words from many threads
ConcurrentHashMap<String, LongAdder> counts = new ConcurrentHashMap<>();
words.parallelStream().forEach(w -> counts.computeIfAbsent(w, k -> new LongAdder()).increment());
// or with merge
ConcurrentHashMap<String, Integer> c = new ConcurrentHashMap<>();
c.merge(word, 1, Integer::sum);Examples
The race you must avoid
// Not atomic: two threads can both read 5 and both write 6
Integer v = map.get(key);
map.put(key, v == null ? 1 : v + 1);
// Atomic
map.merge(key, 1, Integer::sum);Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Build a thread-safe in-memory rate limiter with ConcurrentHashMap and AtomicInteger.
- Write a producer-consumer with ArrayBlockingQueue.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Why does ConcurrentHashMap not allow null keys or values?
In a concurrent map, get returning null would be ambiguous: is the key missing, or mapped to null? You cannot check with containsKey safely because another thread may change it in between, so nulls are forbidden.
Are ConcurrentHashMap iterators fail-fast?
No, they are weakly consistent: they never throw ConcurrentModificationException and reflect some or all changes made during iteration.
Summary
ConcurrentHashMap gives lock-free reads and per-bin locking for writes; use merge and compute for atomic updates, and choose CopyOnWriteArrayList or BlockingQueue for their specific patterns.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus