How Java's ConcurrentHashMap Delivers High‑Performance Thread Safety

This article explains the internal design of Java's ConcurrentHashMap, covering its evolution from JDK7 to JDK8, the segment‑based locking mechanism, lock‑free reads, CAS operations, table resizing, treeification, and the key classes and methods that enable efficient concurrent access while maintaining thread safety.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
How Java's ConcurrentHashMap Delivers High‑Performance Thread Safety

Because HashMap is not thread‑safe, older JDK versions provided Hashtable with synchronized methods, but its heavyweight lock caused poor performance. ConcurrentHashMap solves this by using lock‑splitting and lock‑free reads.

JDK7 Implementation

In JDK7, ConcurrentHashMap consists of a Segment array and a HashEntry array. Each Segment extends ReentrantLock and acts as an independent lock, allowing concurrent updates on different segments.

static final class Segment<K,V> extends ReentrantLock implements Serializable { ... }

Key operations:

put : locate the segment, acquire its lock, then insert or update the entry.

get : lock‑free; compute the hash, locate the segment and traverse the linked list.

size : try a few lock‑free counts; if inconsistent, lock all segments and recount.

rehash : double the segment table size; only the segment lock is held.

JDK8 Redesign

JDK8 removes the Segment array. The table itself stores Node objects, and each bucket can become a red‑black tree when the chain length exceeds a threshold. Lock granularity is reduced to a single bucket, using synchronized on that node and CAS for lock‑free reads.

static final class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; volatile V val; volatile Node<K,V> next; }

Important classes: Node: basic entry. TreeNode: extends Node for red‑black tree nodes. ForwardingNode: marks a bucket that has been moved during resizing. TreeBin: wraps a tree of TreeNode objects.

Core Methods

initTable lazily creates the table with a size based on sizeCtl. Only one thread performs initialization; others yield.

private final Node<K,V>[] initTable() { ... }

putVal computes the hash, attempts a CAS insertion for an empty bucket, otherwise synchronizes on the bucket node and either appends to the list or delegates to TreeBin for tree insertion.

final V putVal(K key, V value, boolean onlyIfAbsent) { ... }

get performs a lock‑free lookup using Unsafe.getObjectVolatile to read the latest bucket value. public V get(Object key) { ... } addCount updates baseCount and, if necessary, triggers resizing. It uses a striped counter array similar to LongAdder to reduce contention.

private final void addCount(long x, int check) { ... }

resizeStamp and sizeCtl encode the resize state; a negative sizeCtl indicates an ongoing resize, while the high‑order bits store a stamp that helps threads coordinate the resize.

transfer moves entries from the old table to the new one. Multiple threads can help; each claims a range of buckets using transferIndex, marks processed buckets with a ForwardingNode, and finally installs the new table.

final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) { ... }

treeifyBin converts a long bucket list into a red‑black tree when the threshold is exceeded, provided the table is large enough; otherwise it triggers a resize.

private final void treeifyBin(Node<K,V>[] tab, int index) { ... }

clear iterates over the table, nulling each bucket with CAS and adjusting the count.

public void clear() { ... }

In summary, ConcurrentHashMap achieves thread safety with lock‑free reads, fine‑grained bucket locks, CAS‑based updates, and a collaborative resizing algorithm that allows multiple threads to participate without blocking normal operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

thread safetyCASConcurrentHashMapResizeRed-Black TreeLock Splitting
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.