Video in progress

Strong Middle 🧺 Collections

What kind of locking does Java 8+ ConcurrentHashMap use for writes, and what happens during a resize?

An element goes into an empty bucket with CAS, without a lock. In an occupied bucket, synchronized is taken only on the first node of that bucket. During a resize, several threads split the work, and buckets that have been moved are marked with a ForwardingNode.

📖 Answer

The Segments from Java 7 (16 separate locks) were removed in Java 8. Now the lock granularity is a single bucket.

putVal works roughly like this:

  1. If there is no table yet, it is created lazily.
  2. If the bucket is empty, a new Node is placed with casTabAt, no lock.
  3. If the bucket holds a ForwardingNode (hash = MOVED), a resize is in progress right now, and the current thread helps with the transfer (helpTransfer).
  4. Otherwise, synchronized (f), where f is the first node in the bucket. The update happens inside the chain or tree.

Reads (get) take no lock at all: Node.val and next are volatile, and the table elements are read as volatile through Unsafe/VarHandle.

During a resize the table is divided into chunks (strides), and each thread moves its own chunk. In place of a moved bucket a ForwardingNode is left, and get is redirected through it to the new table. So reads don't stop even during a resize.

The counter is similar to the LongAdder idea: baseCount and CounterCell[]. That is why size() is not expensive, but it is not exact while other threads are writing.

In practice: ConcurrentHashMap accepts neither a null key nor a null value, so that when get returns null it definitely means "absent".