How ConcurrentHashMap works inside
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ConcurrentHashMap is fast because it almost never makes a thread wait: reads take no lock, a write locks only the one bucket it touches, and a write into an empty bucket takes no lock at all. This is a favourite interview topic, and the ideas fit in a few pictures.
Buckets and why one big lock is slow
A bucket is one slot of the hash table inside a map. The key's hash code picks the bucket, and keys with the same bucket are chained together.
Like HashMap, a ConcurrentHashMap keeps an array called the table. Each slot is a bucket. To place a key, the map takes its hashCode(), mixes the high bits into the low bits, and keeps only the low bits that fit the table size.
Example 1 · Which bucket does a key go to?
public class BucketIndexDemo { // The same idea HashMap and ConcurrentHashMap use: mix the high bits into the low bits, // then keep only the low bits that fit the table size (a power of two). static int bucketOf(Object key, int tableSize) { int h = key.hashCode(); return (h ^ (h >>> 16)) & (tableSize - 1); }
public static void main(String[] args) { int tableSize = 16; Object[] keys = {1, 2, 17, 33, "Asha", "Bala", "Chirag"};
for (Object key : keys) { System.out.println(key + " -> bucket " + bucketOf(key, tableSize)); } System.out.println("Table of 32: 17 -> bucket " + bucketOf(17, 32)); }}1 -> bucket 1 2 -> bucket 2 17 -> bucket 1 33 -> bucket 1 Asha -> bucket 4 Bala -> bucket 11 Chirag -> bucket 11 Table of 32: 17 -> bucket 17
What this code does
- With a table of 16, only the last 4 bits of the mixed hash code matter, so the keys 1, 17 and 33 share bucket 1, and
BalaandChiragshare bucket 11. Two threads writing1and2touch different buckets and have no reason to wait for each other. - After the table doubles to 32, key 17 moves to bucket 17. This is why a resize must move entries between buckets.
Keys that land in the same bucket are chained together.
Most buckets hold zero or one entry, and two threads working on different keys almost always touch different buckets. A Hashtable or synchronized map still makes them wait, because it has one lock for the whole map. That single lock is the bottleneck: with 8 threads, 7 are usually waiting.
The whole design of ConcurrentHashMap follows from one question: why lock the whole table when a thread needs only one bucket?
Java 7 segments versus locking one bucket at a time
Lock striping means using many locks, each guarding a small part of the data, instead of one lock for everything. Threads wait only when they need the same part.
In Java 7, the map was split into segments: by default 16 small hash tables, each with its own lock (each segment was a ReentrantLock). A write locked only its segment, so up to 16 writers could work at the same time.
Example 2 · A model of Java 7 segments (lock striping)
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.locks.ReentrantLock;
// A simplified model of the Java 7 design: 16 small maps ("segments"), each with its own lock.class SegmentedMap<K, V> { private static final int SEGMENTS = 16; private final List<Map<K, V>> maps = new ArrayList<>(); private final List<ReentrantLock> locks = new ArrayList<>();
SegmentedMap() { for (int i = 0; i < SEGMENTS; i++) { maps.add(new HashMap<>()); locks.add(new ReentrantLock()); } }
private int segmentOf(K key) { int h = key.hashCode(); return (h ^ (h >>> 16)) & (SEGMENTS - 1); }
void put(K key, V value) { int s = segmentOf(key); locks.get(s).lock(); // lock only 1 of the 16 segments try { maps.get(s).put(key, value); } finally { locks.get(s).unlock(); } }
int size() { int total = 0; for (int s = 0; s < SEGMENTS; s++) { locks.get(s).lock(); try { total += maps.get(s).size(); } finally { locks.get(s).unlock(); } } return total; }}
public class SegmentModelDemo { public static void main(String[] args) throws InterruptedException { SegmentedMap<Integer, String> results = new SegmentedMap<>(); List<Thread> threads = new ArrayList<>(); for (int t = 0; t < 4; t++) { int first = t * 25_000; Thread th = new Thread(() -> { for (int roll = first; roll < first + 25_000; roll++) { results.put(roll, "PASS"); // threads in different segments do not wait } }, "writer-" + (t + 1)); threads.add(th); th.start(); } for (Thread th : threads) { th.join(); } System.out.println("Stored: " + results.size()); }}Stored: 100000
What this code does
- This is a simplified model, not the real JDK code. Each of the 16 small maps has its own
ReentrantLock, so a writer locks one sixteenth of the data and threads on different segments run in parallel. size()must lock every segment in turn to add up the counts. Java 7's real map first tried counting without locks and locked all segments only if the numbers kept changing.
This idea, many locks each guarding a part of the data, is called lock striping. Example 2 is a small model of it.
Java 8 removed segments. Now every bucket is its own unit of locking: a write takes synchronized on the first node of its bucket. With a table of thousands of buckets, two writers collide only if their keys share a bucket. Memory use also dropped, because there are no segment objects.
The old constructor new ConcurrentHashMap<>(capacity, loadFactor, concurrencyLevel) still exists. Since Java 8, concurrencyLevel is only a hint for the starting table size.
Reads without locks, empty buckets filled with compare-and-set
A get takes no lock at all. The table slots are read with volatile semantics, and each node's value and next link are volatile fields, so a reader always sees a fully built node that another thread published.
Example 3 · A model of filling empty buckets with compare-and-set
import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicReferenceArray;
// A simplified model of how ConcurrentHashMap fills an EMPTY bucket: compare-and-set, no lock.public class CasBucketDemo { static final int BUCKETS = 1_000; static final AtomicReferenceArray<String> table = new AtomicReferenceArray<>(BUCKETS); static final AtomicInteger casWins = new AtomicInteger(); static final AtomicInteger casLosses = new AtomicInteger();
static void putIntoEmptyBucket(int bucket, String value) { // "if the slot is still null, put my node there" as ONE atomic step if (table.compareAndSet(bucket, null, value)) { casWins.incrementAndGet(); } else { casLosses.incrementAndGet(); // someone was first: the real map retries and locks the bucket } }
public static void main(String[] args) throws InterruptedException { Thread a = new Thread(() -> { for (int b = 0; b < BUCKETS; b++) { putIntoEmptyBucket(b, "from-A"); } }, "thread-A"); Thread c = new Thread(() -> { for (int b = 0; b < BUCKETS; b++) { putIntoEmptyBucket(b, "from-B"); } }, "thread-B"); a.start(); c.start(); a.join(); c.join();
int filled = 0; for (int b = 0; b < BUCKETS; b++) { if (table.get(b) != null) { filled++; } } System.out.println("Buckets filled: " + filled); System.out.println("CAS wins: " + casWins.get() + ", CAS losses: " + casLosses.get()); }}Buckets filled: 1000 CAS wins: 1000, CAS losses: 1000
What this code does
- Two threads race to fill the same 1,000 empty slots with
compareAndSet(i, null, value). For every slot exactly one wins, so there are exactly 1,000 wins and 1,000 losses on every run, with no lock. - Which thread wins each slot changes from run to run. In the real map, the losing thread re-reads the bucket, finds a node there, and continues on the locked path.
That is why lookups never wait for writers, as the night-report example in "ConcurrentHashMap basics" showed.
A put into an empty bucket also takes no lock. The map uses compare-and-set (CAS): "if this slot is still null, put my node there", done as one hardware instruction. If two threads try at once, exactly one succeeds; the other sees the slot is no longer empty and goes the slow way. Example 3 is a model of this race.
The slow way is for buckets that already have nodes: the thread locks the bucket's first node with synchronized, walks the chain, then replaces the value or adds a node at the end. Only threads that need the same bucket ever wait.
get: no lock, volatile reads.put, empty bucket: CAS, no lock.put, bucket with nodes:synchronizedon that bucket's first node only.size(): adds up a base counter and extra counter cells (likeLongAdder), so it never locks the map.
Order of execution
A put into a bucket that already has nodes
Tap the steps in the order the map does them.
Resizing and tree bins in simple terms
When the map holds more than about 75% of its table size (the load factor), it resizes: it creates a table twice as big and moves every bucket across. Instead of one thread doing all the work while everyone waits, the resize is shared.
Example 4 · 20,000 keys in one bucket still work
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;
// Every key has the same hash code, so every key lands in the same bucket.record PnrKey(int number) implements Comparable<PnrKey> { @Override public int hashCode() { return 42; // a terrible hash code, on purpose }
@Override public int compareTo(PnrKey other) { return Integer.compare(number, other.number); // helps the tree bin order its keys }}
public class BadHashDemo { public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<PnrKey, String> bookings = new ConcurrentHashMap<>(); List<Thread> threads = new ArrayList<>(); for (int t = 0; t < 4; t++) { int first = t * 5_000; Thread th = new Thread(() -> { for (int n = first; n < first + 5_000; n++) { bookings.put(new PnrKey(n), "CONFIRMED"); } }, "booking-" + (t + 1)); threads.add(th); th.start(); } for (Thread th : threads) { th.join(); }
boolean allFound = true; for (int n = 0; n < 20_000; n++) { if (!"CONFIRMED".equals(bookings.get(new PnrKey(n)))) { allFound = false; } } System.out.println("Bookings stored: " + bookings.size()); System.out.println("Every PNR found: " + allFound); }}Bookings stored: 20000 Every PNR found: true
What this code does
- Every
PnrKeyreturns hash code 42, so all 20,000 keys share one bucket and all four threads compete for that bucket's lock. The map stays correct: every booking is stored and found. - Because the bucket is large,
ConcurrentHashMapstores it as a tree bin ordered withcompareTo, so a lookup takes about 15 steps instead of up to 20,000. A goodhashCodewould avoid both the slow lookups and the single shared lock.
Any thread that tries to write during a resize helps move a chunk of buckets. Each moved bucket gets a marker node that sends readers to the new table, so get keeps working throughout.
If many keys land in one bucket (usually because of a poor hashCode), a chain gets long and searching it is slow. Once a bucket reaches 8 nodes and the table has at least 64 buckets, the map turns that chain into a tree bin: a balanced red-black tree. Finding a key then takes about log₂ n steps instead of n. When a bucket shrinks to 6 or fewer, it goes back to a simple chain. (With a smaller table, the map simply resizes instead.)
Trees help most when the key class implements Comparable, as in Example 4. The best fix is still a good hashCode.
ConcurrentHashMap versus Hashtable and synchronizedMap
All three are thread-safe for single calls. The difference is how much threads wait, and a few rules around null and iteration.
Example 5 · Timing the three thread-safe maps
import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Hashtable;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
public class ThreeMapsTimingDemo { static long run(Map<Integer, Integer> map) throws InterruptedException { for (int k = 0; k < 1_000; k++) { map.put(k, 0); } List<Thread> threads = new ArrayList<>(); long start = System.nanoTime(); for (int t = 0; t < 8; t++) { Thread th = new Thread(() -> { for (int i = 0; i < 300_000; i++) { int key = i % 1_000; if (i % 10 == 0) { map.put(key, i); // 10% writes } else { map.get(key); // 90% reads } } }, "client-" + t); threads.add(th); th.start(); } for (Thread th : threads) { th.join(); } return (System.nanoTime() - start) / 1_000_000; }
public static void main(String[] args) throws InterruptedException { for (int round = 1; round <= 2; round++) { // round 1 warms up the JVM long a = run(new Hashtable<>()); long b = run(Collections.synchronizedMap(new HashMap<>())); long c = run(new ConcurrentHashMap<>()); if (round == 2) { System.out.println("Hashtable: " + a + " ms"); System.out.println("synchronizedMap: " + b + " ms"); System.out.println("ConcurrentHashMap: " + c + " ms"); } } }}Hashtable: 79 ms synchronizedMap: 101 ms ConcurrentHashMap: 13 ms
What this code does
- Eight threads do 2.4 million mostly-read operations on each map. On the 12-core laptop that made this sample,
ConcurrentHashMapwas several times faster, because its reads never wait for a lock. - Your numbers will differ from run to run and machine to machine, and a quick timing like this is only a rough guide. The gap grows with more threads and more reads.
- Locking:
HashtableandsynchronizedMapuse one lock for every call;ConcurrentHashMaplocks one bucket for writes and nothing for reads. - Iteration: the first two need
synchronized (map)around loops and can throw a CME;ConcurrentHashMaploops are weakly consistent and never throw. null:HashtableandConcurrentHashMapreject it;synchronizedMapfollows the wrapped map (aHashMapallows it).- Atomic updates: all have
putIfAbsent,mergeandcompute, but onlyConcurrentHashMapruns them while other threads keep working on other keys.
ConcurrentHashMap for any shared map with real traffic. Keep synchronizedMap for rare cases such as wrapping a TreeMap (for a sorted concurrent map, ConcurrentSkipListMap also exists).Next step
Check your understanding
12 quick questions