Java core learning path Level 4 This level · 2 of 4
Hard java java-21

How does ConcurrentHashMap work internally?

The 30 second answer

ConcurrentHashMap lets many threads read and write without locking the whole map. Reads usually don't block, and writes only lock a small part of the table, so writers on different keys rarely wait for each other. Methods like compute, computeIfAbsent and merge are atomic per key. Size is only an estimate during updates, iterators never throw concurrent modification errors, and null keys or values aren't allowed.

Could you say this in an interview?

What the Javadoc guarantees:

  • Retrievals generally don't block and reflect the most recently completed updates.
  • compute, computeIfAbsent, computeIfPresent and merge run atomically per key. Keep those functions short and never update other keys of the same map inside them.
  • size(), isEmpty() and containsValue() are only reliable when the map isn't being updated; mappingCount() returns a long.
  • Iterators are weakly consistent: they never throw ConcurrentModificationException and may or may not show updates made during iteration.
  • Null keys and values are rejected, so get returning null always means "absent".
ConcurrentHashMap<String, LongAdder> counts = new ConcurrentHashMap<>();
counts.computeIfAbsent(word, k -> new LongAdder()).increment();   // safe

if (!map.containsKey(k)) map.put(k, v);   // NOT atomic: check-then-act race
map.putIfAbsent(k, v);                    // atomic

[Impl] Since Java 8 the OpenJDK implementation no longer uses Java 7's segments: it uses CAS to insert into an empty bin, locks only the bin's first node for other updates, turns long bins into balanced trees, and lets several threads help with resizing. These details come from source-code comments, not the public spec, and can change.

Alternate interview scenarios

"How does a plain HashMap work internally, how are collisions handled since Java 8, and why is the default load factor 0.75?"

HashMap keeps an array of buckets whose size is a power of two. In OpenJDK, put spreads the key's hashCode by mixing its high bits into the low bits, picks the bucket from the low bits, and compares entries by hash and then equals. Keys that land in the same bucket are chained. Since Java 8 the OpenJDK implementation turns a long chain into a red-black tree once a bin reaches eight nodes and the table has at least sixty-four buckets; below that capacity it resizes instead, and a shrunk tree turns back into a list. That bounds the worst case when many keys collide, and tree ordering works best when keys are Comparable. These are implementation details from source comments, not the public contract. When size exceeds capacity times load factor, the table doubles and entries are redistributed. The Javadoc only says the default load factor of 0.75 offers a good trade-off between time and space; the source comments add that with well-distributed hashes, bin sizes then follow roughly a Poisson distribution with a small mean, so long chains are rare. If I know the size, I set the initial capacity so it never resizes. HashMap itself is not thread-safe.

Sources (4)
  1. ConcurrentHashMap Javadoc (Java 21)docs.oracle.com
  2. ConcurrentMap Javadocdocs.oracle.com
  3. HashMap Javadoc (Java 21): capacity, load factor and rehashingdocs.oracle.com
  4. OpenJDK 21 HashMap source (hash spreading, treeify thresholds, Poisson note)github.com
Previous
Next