Video in progress

Strong Middle 🧵 Concurrency

How is ConcurrentHashMap structured internally in Java 8 and later?

There are no segments: an empty bucket is written with CAS, and in an occupied bucket only the first node of that bucket is locked. Reads are lock-free, a long chain turns into a tree, and several threads can do a resize together.

📖 Answer

In Java 7 the map was split into 16 segments, each with its own lock. Java 8 rewrote this completely.

A write (putVal) goes roughly like this:

  1. If the table doesn't exist yet, it's created with CAS.
  2. If the bucket is empty, the new node is placed with CAS, with no lock at all.
  3. If the bucket holds a MOVED marker, a resize is in progress and the thread helps with it (helpTransfer).
  4. Otherwise it does synchronized on the first node of the bucket and adds to the chain or the tree inside.

A read (get) takes no lock: val and next in the nodes are volatile, and the table elements are read with volatile semantics through Unsafe/VarHandle.

Other details:

  • If a chain grows past 8 nodes and the table is at least 64 long, the bucket turns into a red-black tree.
  • size() uses baseCount and CounterCell[], an idea similar to LongAdder, so under load the result is approximate.
  • Both null keys and null values are forbidden: if get returned null, you couldn't tell "absent" from "null stored".

In practice the most common mistake isn't in the map itself but in how it's used: if (!map.containsKey(k)) map.put(k, v) is not atomic. For that there are putIfAbsent, computeIfAbsent and merge.