ConcurrentHashMap
Give a real production-style example of using ConcurrentHashMap. Walk through the scenario end-to-end.
Answers use simple, clear English.
Quick interview answer
Scenario: Rate limiter stores token counts per API key updated from many threads concurrently. Implementation notes: Use compute/merge; avoid locking entire map for single-key updates.
Detailed answer
Scenario: Rate limiter stores token counts per API key updated from many threads concurrently. Implementation notes: Use compute/merge; avoid locking entire map for single-key updates. 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: Junior.
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?