Video in progress
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:
- If the table doesn't exist yet, it's created with CAS.
- If the bucket is empty, the new node is placed with CAS, with no lock at all.
- If the bucket holds a
MOVEDmarker, a resize is in progress and the thread helps with it (helpTransfer). - Otherwise it does
synchronizedon 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()usesbaseCountandCounterCell[], an idea similar toLongAdder, so under load the result is approximate.- Both
nullkeys andnullvalues are forbidden: ifgetreturned 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.
Sign up to mark studied questions and save your progress.