ConcurrentHashMap
As a Fresher engineer, explain ConcurrentHashMap. What problem does it solve and how would you describe it in an interview?
Answers use simple, clear English.
Quick interview answer
At Fresher depth: start with the problem, then mechanism, then a short example. Thread-safe map with fine-grained locking/CAS.
Detailed answer
At Fresher depth: start with the problem, then mechanism, then a short example. Thread-safe map with fine-grained locking/CAS. compute/merge methods atomic per key. Weakly consistent iterators — no ConcurrentModificationException. Core: Thread-safe map with fine-grained locking/CAS. compute/merge methods atomic per key. Weakly consistent iterators — no ConcurrentModificationException. Real-time example: Rate limiter stores token counts per API key updated from many threads concurrently. Pros: Better than Hashtable/synchronizedMap for high concurrency. Cons: Compound actions across keys need external locking; not for strong iteration snapshot. Common mistakes: if (!map.containsKey(k)) map.put(k,v) race — use putIfAbsent or compute. Best practices: Use compute/merge; avoid locking entire map for single-key updates. Audience level: Fresher.
Full explanation
Thread-safe map with fine-grained locking/CAS. compute/merge methods atomic per key. Weakly consistent iterators — no ConcurrentModificationException.
Real example & use case
Rate limiter stores token counts per API key updated from many threads concurrently.
Pros & cons
Pros: Better than Hashtable/synchronizedMap for high concurrency. Cons: Compound actions across keys need external locking; not for strong iteration snapshot.
Common mistakes
if (!map.containsKey(k)) map.put(k,v) race — use putIfAbsent or compute.
Best practices
Use compute/merge; avoid locking entire map for single-key updates.
Follow-up questions
- How would you test ConcurrentHashMap?
- What metrics prove ConcurrentHashMap is healthy in prod?
- How does ConcurrentHashMap change at 10× traffic?