☕ Java
Advanced
What is ConcurrentHashMap and how does it differ from HashMap?
Answer
ConcurrentHashMap is a thread-safe implementation of HashMap designed for high-concurrency scenarios. Unlike Hashtable (which locks the entire map), ConcurrentHashMap uses lock striping — in Java 8, it uses CAS (Compare-And-Swap) operations and synchronized blocks on individual buckets, allowing concurrent reads and writes to different buckets simultaneously. This gives far better throughput than full synchronization. Reads (get) never block. ConcurrentHashMap does not allow null keys or values (to avoid ambiguity between a missing key and a key mapped to null). For atomic compound operations, use methods like putIfAbsent(), computeIfAbsent(), and merge().