collections
advanced

ConcurrentHashMap

A thread-safe Map with concurrent reads and finely-grained writes — without locking the entire map.

ConcurrentHashMap is the standard answer when several threads share a map. The older options force a bad trade: a plain HashMap is fast but unsafe under concurrent writes, while Collections.synchronizedMap or the legacy Hashtable are safe but serialise every operation behind a single lock, so threads queue up even for unrelated keys. ConcurrentHashMap keeps the safety while letting genuinely independent operations proceed in parallel.

A library with one lock per shelf instead of one lock for the whole building. Many readers and writers can work in parallel as long as they're not at the same shelf.

Key Concepts

1
It achieves this with fine-grained locking. Reads are essentially lock-free — values and next-pointers are volatile, so a reader sees a consistent view without acquiring anything. Writes lock only the individual bucket being modified (in modern Java, synchronising on the first node of that bin, or using a CAS to install the first node of an empty bin), rather than the whole table. The result is high read throughput and write contention only between threads touching the same bucket. It also forbids null keys and values, partly so that a null return from get unambiguously means "absent" rather than "present but null" in a concurrent setting.
volatileget
2
Two subtleties matter in interviews. First, atomicity is per-operation, not across operations: a get followed by a put is two separate atomic steps and another thread can interleave between them, which is why compound actions should use the atomic methods putIfAbsent, compute, and merge. Second, its iterators are weakly consistent — they never throw ConcurrentModificationException and reflect some, but not necessarily all, concurrent updates. Aggregate methods like size() are therefore estimates under active modification.
getputputIfAbsentcomputemerge