ConcurrentHashMap
Implement or sketch code for ConcurrentHashMap. Explain the logic, complexity, and pros/cons of this approach.
Answers use simple, clear English.
Quick interview answer
Logic: Thread-safe map with fine-grained locking/CAS. compute/merge methods atomic per key.
Detailed answer
Logic: Thread-safe map with fine-grained locking/CAS. compute/merge methods atomic per key. Weakly consistent iterators — no ConcurrentModificationException. Complexity notes included in code section when present. Pros: Better than Hashtable/synchronizedMap for high concurrency. Cons: Compound actions across keys need external locking; not for strong iteration snapshot. 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: Architect.
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.
Code example
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
void increment(String key) {
counts.merge(key, 1, Integer::sum);
}
int get(String key) {
return counts.getOrDefault(key, 0);
}Practice code · java (view only · no execution)
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
void increment(String key) {
counts.merge(key, 1, Integer::sum);
}
int get(String key) {
return counts.getOrDefault(key, 0);
}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?