ConcurrentHashMap
For campus/fresher interviews: what is ConcurrentHashMap in simple terms, with one tiny example?
Answers use simple, clear English.
Audio N/AQuick interview answer
Simple view: Thread-safe map with fine-grained locking/CAS. compute/merge methods atomic per key.
Detailed answer
Simple view: Thread-safe map with fine-grained locking/CAS. compute/merge methods atomic per key. Weakly consistent iterators — no ConcurrentModificationException. Tiny example: Rate limiter stores token counts per API key updated from many threads concurrently. 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?