Two threads share one HashMap, both add 1 to the same counter, and the counter ends at 1. Nothing throws, nothing is logged, and the bug only shows up under load. That single failure is why interviewers keep asking about HashMap versus ConcurrentHashMap, and why the honest answer is longer than “one is thread-safe and the other is not”.
This guide starts with that failure, builds the mental model of both maps, then opens up the JDK 25 source: the sizeCtl field, how bins turn into trees, why ConcurrentHashMap still loses updates if you use it the wrong way, and which fixes are exact. Ten interview answers and the original question bank follow. Every number comes from code in the companion module.
Versions. All new material (internals, lost updates, recursion, nulls) was run on JDK 25.0.5+8 (Temurin, LTS) with JUnit 6.1.3 and Maven 3.9.11, on a 2-vCPU Linux VM, and cross-checked againstHashMap.javaandConcurrentHashMap.javafrom that JDK’s ownlib/src.zip. The JMH throughput table further down was measured earlier on JDK 25.0.4.1+1 with JMH 1.37 and was not re-run for this rewrite. Lost-update counts differ on every run; the tests assert only deterministic facts.
Two threads, one map: the lost update
A map is a shared variable with a fancy interface. If two threads read the value, add one, and write it back, whichever write lands last wins and the other increment disappears. The diagram shows the exact order of events.
The picture says: thread A and thread B both read 0 (steps 1 and 2) before either writes (steps 3 and 4). Both write 1. The important point for interviews is that get and put can each be fully thread-safe and the pair is still wrong, because nothing makes the pair one indivisible step.
To see it without waiting for bad luck, the test below forces that order with a latch: each thread reads, then waits until both have read, then writes. The method is in ForcedInterleavingTest.java.
static int forcedLostUpdate(Map<String, Integer> map) throws Exception {
map.put("n", 0);
CountDownLatch bothRead = new CountDownLatch(2);
Runnable r = () -> {
int seen = map.get("n"); // step 1: read
bothRead.countDown();
try {
if (!bothRead.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("timeout");
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
map.put("n", seen + 1); // step 2: write based on the stale read
};
Thread a = new Thread(r), b = new Thread(r);
a.start(); b.start();
a.join(); b.join();
return map.get("n");
}
Result, from 04-forced-lost-update.txt (deterministic, asserted by the test):
expected final value: 2
HashMap get + put: 1
synchronizedMap get + put: 1
ConcurrentHashMap get + put: 1
ConcurrentHashMap merge: 2
(each map call is individually thread-safe; the get-then-put PAIR is not atomic)
All three maps give 1. That includes ConcurrentHashMap: it protects each call, not your sequence of calls. The fix is to make the read-modify-write one call (merge, compute), shown two sections down.
Fingerprint of this bug. A counter, a “seen so far” total or a balance that is slightly low, differs on every run, and disappears when you add logging or a debugger (which change the timing). No exception, no stack trace.
Going deeper
- ForcedInterleavingTest.java — the forced interleaving, plus the
mergefix - Brian Goetz et al., Java Concurrency in Practice, chapter 2 (compound actions, check-then-act)
HashMap in one picture
HashMap is a hash table. It keeps an array of bins (buckets). To store a key it computes a number from the key, squeezes that number into an array index, and puts the entry in that bin. Two keys in the same bin is a collision; the bin then holds a chain of entries (and, for long chains in a big enough table, a tree).
Read the picture top to bottom: most bins are empty or hold one node, one bin holds a short chain, and one bin has been converted to a tree. The footer states the three rules the rest of this article keeps using: index is (n - 1) & hash, resize happens at 75% full, and a tree needs both a long chain and a table of at least 64 bins.
HashMap is a hash table based implementation of the Map interface in java.util. It stores key-value pairs and gives constant-time get() and put() as long as the hash function spreads keys well. Internally it is an array of buckets, each a linked list (or red-black tree) of entries; the bucket is chosen from the key’s hash.
- Initial capacity: 16 (read from the running JDK:
DEFAULT_INITIAL_CAPACITY = 16) - Load factor: 0.75
- Threshold: the point where resizing happens (capacity × load factor, so 12 for 16)
- Bucket: each index in the table array
- Collision: two keys that land in the same bucket
- Treeify threshold: 8, but with a second condition: see the next section
The constants are not copied from a blog. The test Jdk25ConstantsTest reads them from the loaded classes; the file is 01-jdk-constants.txt:
java.util.HashMap
DEFAULT_INITIAL_CAPACITY = 16
MAXIMUM_CAPACITY = 1073741824
DEFAULT_LOAD_FACTOR = 0.75
TREEIFY_THRESHOLD = 8
UNTREEIFY_THRESHOLD = 6
MIN_TREEIFY_CAPACITY = 64
What put() does, step by step
put() hashes the key, picks a bin, and either places a new node, replaces the value of an equal key, or appends to the chain. Then it checks whether the table has grown past its threshold. In order:
- Calculate
hashCode()of the key and mix it with the internalhash()function so high bits influence the low bits used for the index - Compute the index:
(n - 1) & hashwherenis the table length (always a power of two) - If the bin is empty, create a node and place it
- If the bin has entries, walk the chain (or tree) comparing hash and then
equals() - If an equal key is found, replace its value
- Otherwise append a new node at the end of the chain
- If the entry count passed the threshold, resize
The source for this, from the JDK 25.0.5+8 HashMap (excerpts A and A2 in the source excerpts file):
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
Why does the null key work in a HashMap? hash(null) is 0, so the null key lives in bin 0. That is a design choice for flexibility; the nulls section below contrasts it with ConcurrentHashMap.
Going deeper: equals() and hashCode(), collisions, load factor, resize
The contract. Equal objects must have equal hashCode(); equal hash codes do not imply equal objects. Break it and HashMap misbehaves: you put a key and cannot find it. When you use your own class as a key, override both methods together. Mutable keys are dangerous for the same reason: if the field that feeds hashCode() changes after insertion, the entry sits in the old bin and lookups go to the new one. Prefer immutable keys such as String and Integer. Runnable proof (equals without hashCode, and a mutated key) is in the sibling collections module.
Collisions. Entries with colliding hashes share a bin as a chain; lookups walk it using equals(). In Java 8+ a long chain can become a red-black tree (rules in the next section).
Load factor. A lower load factor wastes memory and gives fewer collisions; a higher one saves memory and gives more. The default 0.75 is the standard compromise.
Resize. When the count passes the threshold, the table doubles and entries are redistributed. Because the capacity is a power of two, each entry either stays at its index or moves to index + oldCapacity, so no full rehash is needed.
How a bin becomes a tree in JDK 25 (and why 8 is not the whole story)
The popular answer is “when a bin has more than 8 entries it becomes a tree”. The source says something slightly different. In HashMap.putVal (excerpt B) the new node is appended first and treeifyBin is called when the chain already held 8 nodes, so the trigger is the 9th node:
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
And treeifyBin does not always build a tree. If the table is smaller than MIN_TREEIFY_CAPACITY (64) it resizes instead, on the theory that a crowded small table is better fixed by spreading entries out. The test inserts 12 keys that all have hashCode() == 1 into both maps. Output from 03-treeify-compare.txt (test: TreeifyCompareTest.java):
insert | HashMap table[1] (length) | ConcurrentHashMap table[1] (length, sizeCtl)
#1 | Node (length 16 ) | Node (length 16 , sizeCtl 12)
#2 | Node (length 16 ) | Node (length 16 , sizeCtl 12)
#3 | Node (length 16 ) | Node (length 16 , sizeCtl 12)
#4 | Node (length 16 ) | Node (length 16 , sizeCtl 12)
#5 | Node (length 16 ) | Node (length 16 , sizeCtl 12)
#6 | Node (length 16 ) | Node (length 16 , sizeCtl 12)
#7 | Node (length 16 ) | Node (length 16 , sizeCtl 12)
#8 | Node (length 16 ) | Node (length 16 , sizeCtl 12)
#9 | Node (length 32 ) | Node (length 128, sizeCtl 96)
#10 | Node (length 64 ) | TreeBin (length 128, sizeCtl 96)
#11 | TreeNode (length 64 ) | TreeBin (length 128, sizeCtl 96)
#12 | TreeNode (length 64 ) | TreeBin (length 128, sizeCtl 96)
What the table shows: in HashMap the 9th insert resizes 16 to 32, the 10th resizes 32 to 64, and only the 11th insert finds a table of 64 and converts the bin (the head becomes a TreeNode). ConcurrentHashMap is different in two ways. Its tree root is a separate TreeBin object (a hash of -2 marks it), and its first treeify attempt jumped the table from 16 straight to 128, so the 10th insert already built the tree.
The jump is visible in the source. treeifyBin (excerpt E) calls tryPresize(n << 1), and tryPresize loops while the target size is above sizeCtl (the 0.75 threshold, not the table length), so it doubles 16 → 32 → 64 → 128 until the threshold reaches 96. I read this from the loop and confirmed it with the run above; I did not find it documented.
private final void treeifyBin(Node<K,V>[] tab, int index) {
Node<K,V> b; int n;
if (tab != null) {
if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
tryPresize(n << 1);
Trees are rare in practice. With a decent hashCode() trees are almost never needed: the implementation notes in HashMap.java give the probability of a bin holding 8 entries as 0.00000006 and of holding more as less than 1 in ten million (a Poisson estimate quoted from the source comment, not measured here). Trees exist as a defence against bad or hostile hash codes, turning worst-case O(n) lookups into O(log n). Untreeify happens at 6 (UNTREEIFY_THRESHOLD) when a resize splits a tree or removals shrink it.
Going deeper
- 01-jdk-constants.txt —
TREEIFY_THRESHOLD,UNTREEIFY_THRESHOLD,MIN_TREEIFY_CAPACITYread from the running JDK - HashMap Internal Working in Java: Hashing, Buckets, Resize and Treeification — the dedicated deep dive on this half of the story
- collections/output/04-treeify-trigger.txt — the same HashMap sequence from the sibling module
What a shared HashMap actually does under threads
The forced test proved the bug exists. How often does it bite with real scheduling? LostUpdateDemo (LostUpdateDemo.java) runs 8 threads, each doing 200,000 increments of one key, for 5 rounds per variant. The expected total is 1,600,000. Here is the measured output, trimmed to the first four variants, from 05-measured-lost-updates.txt:
threads=8, increments per thread=200,000, rounds=5, cores=2
Counts below VARY from run to run. Only the 'expected' column is fixed.
HashMap get+put expected 1,600,000 actual per round: 228,496 400,000 287,091 1,200,000 451,357
lost updates per round: min 400,000, max 1,371,504
Collections.synchronizedMap get+put expected 1,600,000 actual per round: 282,588 398,788 918,560 433,831 691,994
lost updates per round: min 681,440, max 1,317,412
ConcurrentHashMap get+put expected 1,600,000 actual per round: 214,096 666,429 605,316 446,831 389,717
lost updates per round: min 933,571, max 1,385,904
HashMap + synchronized(map) around get+put expected 1,600,000 actual per round: 1,600,000 1,600,000 1,600,000 1,600,000 1,600,000
lost updates per round: min 0, max 0
These counts vary run to run. They depend on the CPU count (2 here), scheduling and JIT timing. What does not vary: the unsafe variants lose a large share of the updates, and the locked variants are exact. No test asserts these figures; the deterministic proof is the forced interleaving above.
Three lessons sit in those lines. First, plain HashMap lost between 400,000 and 1,371,504 of 1,600,000 updates across five rounds. Second, Collections.synchronizedMap lost updates as well, because it makes each call atomic but not the get-then-put pair. Third, ConcurrentHashMap with get plus put lost roughly as many as the others; being a concurrent map does not fix a compound action.
A second kind of damage needs no overwriting at all. When threads insert different keys into one HashMap at once, structural changes race (two threads appending to the same chain, or resizing while another inserts). From 05-measured-lost-updates.txt:
HashMap put of distinct keys (size()) expected 400,000 actual per round: 399,522 400,000 400,000 400,000 400,000
lost updates per round: min 0, max 478
HashMap exceptions thrown inside worker threads, per round: [null, null, null, null, null]
ConcurrentHashMap put of distinct keys (size()) expected 400,000 actual per round: 400,000 400,000 400,000 400,000 400,000
lost updates per round: min 0, max 0
In round 1 the map reported 399,522 entries after 400,000 distinct inserts: 478 entries silently vanished. In the other four rounds this run lost nothing, which is exactly why the bug survives code review and testing. Older advice that a concurrent HashMap can loop forever in resize() describes Java 7; I did not observe a hang here and I am not claiming one for JDK 25.
Going deeper: fail-fast iterators and the Hashtable comparison
Fail-fast iterators. HashMap iterators are fail-fast: if the map is structurally modified after the iterator was created (except through the iterator’s own remove), the next call throws ConcurrentModificationException, based on an internal modCount. It is a best-effort bug detector, not a thread-safety mechanism, and it can miss races. Runnable CME reproductions, including a case where it does not fire, are in the sibling module (05, 06, 07).
HashMap vs Hashtable.
| Feature | HashMap | Hashtable |
|---|---|---|
| Thread safety | Not thread-safe | Thread-safe (synchronized methods) |
| Null keys/values | Allows one null key and null values | Does not allow null keys or values |
| Performance | Faster (no synchronization overhead) | Slower due to synchronization |
| Inheritance | Extends AbstractMap | Extends Dictionary |
| Iteration | Fail-fast iterators | keys()/elements() Enumerations are not fail-fast; the Iterator views are (its inner Enumerator implements both) |
Making a HashMap safe: Collections.synchronizedMap(new HashMap<>()) (one lock for every call), ConcurrentHashMap (bin-level locking, usually the right answer), or your own external locking (as in the synchronized (map) variant above).
How ConcurrentHashMap stays safe without one big lock
ConcurrentHashMap (CHM) is the thread-safe sibling, in java.util.concurrent since Java 5. Since Java 8 it has the same table-of-bins layout as HashMap but changes how threads touch it: reads take no lock, writes to an empty bin use a compare-and-swap, and writes to a non-empty bin lock only that bin’s first node. The diagram lists the four paths a put can take.
Read it as a decision tree: the thread inspects the bin and takes the cheapest safe path. Only the right-hand path acquires a lock, and it is the lock on one node, so two threads writing different bins never wait for each other. Here is the start of putVal from the JDK (excerpt D):
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh; K fk; V fv;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
JDK 25.0.5+8 source, excerpt D: source excerpts file.
Key concepts, with the Java 7 ones marked as history:
- Segment (Java 7 only): an independent partition with its own lock; removed in Java 8
- Concurrency level: Java 7 segment count; a sizing hint only in JDK 8+ (correction below)
- Volatile variables: table slots and node fields are read with volatile semantics so changes are visible across threads
- CAS (compare-and-swap): the lock-free primitive used for empty-bin inserts, counters and
sizeCtl
That is what “bucket-level locking” means in JDK 8 and later. The Java 7 design (16 Segment locks) is gone; the word “striping” is still used loosely, but there are no fixed stripes now.
Correction to a common answer. “Concurrency level 16 means 16 threads can write at once” was true of Java 7 segments. In JDK 25 the 3-argument constructor treatsconcurrencyLevelonly as a sizing hint: it raises the initial capacity to at least that number and then discards it (excerpt C below). The constantDEFAULT_CONCURRENCY_LEVEL = 16still exists, but in this source it is used only inwriteObject, to keep the serialized form compatible. Many online answers, and the earlier version of this article, got this wrong.
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (initialCapacity < concurrencyLevel) // Use at least as many bins
initialCapacity = concurrencyLevel; // as estimated threads
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}
Notice also the sizing: the capacity you pass is divided by the load factor. new ConcurrentHashMap<>(32) allocates 64 bins where new HashMap<>(32) allocates 32. Both are in 02-sizectl-lifecycle.txt, below.
sizeCtl: one int that means four things
CHM has no threshold field. A single volatile int called sizeCtl does the job, and its meaning depends on the table’s state. From the field’s own comment and the code: before the table exists it holds the initial size (0 means default); after initialization it holds the next resize threshold; while one thread is initializing it is -1; during a resize it is negative.
I read sizeCtl, table and baseCount by reflection through a map’s life (test SizeCtlTest, output 02-sizectl-lifecycle.txt):
new ConcurrentHashMap() sizeCtl=0 table=null
after 1st put sizeCtl=12 table.length=16
after 12 puts (size=12) sizeCtl=24 table.length=32
baseCount=12 counterCells=null size()=12 mappingCount()=12 (single thread: no CounterCell was ever needed)
Sizing constructors: ask for 32 and see what each map really allocates
new ConcurrentHashMap(32) sizeCtl=64 (table not allocated yet)
after 1st put sizeCtl=48 table.length=64
new HashMap(32) threshold=32 table=null (threshold holds the initial capacity until first put)
after 1st put threshold=24 table.length=32
What sizeCtl holds while a resize is running (computed, not caught live):
resizeStamp(16)=32795 (rs << 16) + 2 = -2145714174 -> negative, so every other thread sees 'resize in progress'
Reading it: a fresh map has sizeCtl=0 and no table. The first put runs initTable() (excerpt G), which CASes sizeCtl to -1 so only one thread allocates, creates 16 bins, and stores 12 (that is n - (n >>> 2), i.e. 0.75n). On the 12th element the count reaches sizeCtl and the table doubles to 32 with threshold 24. Note this differs by one from HashMap, which resizes when the size exceeds the threshold.
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {
try {
if ((tab = table) == null || tab.length == 0) {
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
JDK 25.0.5+8 source, excerpt G: source excerpts file.
The last line shows the in-resize value. While a resize runs, sizeCtl holds (resizeStamp(n) << 16) + 2 for the first resizing thread, which is negative; I computed it with the real resizeStamp method but did not catch it live, because the window is too short to observe deterministically. The field comment in the source describes the value as -(1 + the number of active resizing threads), while addCount and tryPresize in the same source store the stamp-based value, so treat that comment as out of date. Other threads that arrive at a moved bin (a ForwardingNode, hash -1) do not wait; they call helpTransfer and each claims a stride of bins (at least 16) to copy. That is how a big CHM resizes in parallel.
size() is a sum, not a field
CHM does not keep one shared counter that every writer must fight over. It keeps a baseCount and, under contention, an array of CounterCells, and size() adds them up (excerpt F). In the single-threaded run above counterCells stayed null and baseCount was 12. The old claim that size() “iterates through all segments” describes Java 7. In JDK 25 the result is a snapshot that can be stale while writers are active; mappingCount() returns the same sum as a long and is the better call for very large maps.
final long sumCount() {
CounterCell[] cs = counterCells;
long sum = baseCount;
if (cs != null) {
for (CounterCell c : cs)
if (c != null)
sum += c.value;
}
return sum;
}
JDK 25.0.5+8 source, excerpt F: source excerpts file.
Going deeper: reads, iterators and memory
Reads. get() never locks. Table slots and node fields are read with volatile semantics, so a reader sees either the old or the new state of a bin, never a half-built one. Reads can run during writes and during a resize (a reader that meets a ForwardingNode follows it to the new table).
Iterators. CHM iterators are weakly consistent: they reflect the map at some point at or after creation, may or may not show later changes, and never throw ConcurrentModificationException. Safe to iterate while others update; do not rely on seeing a given update.
Memory. A little more per map than HashMap (counter cells, forwarding nodes during resize), nothing per entry beyond the node.
Going deeper
- HashMap-ConcurrentHashMap-JDK25-source-excerpts.txt — the source excerpts used above, with file and line ranges
- SizeCtlTest.java — the reflection that produced the sizeCtl output
- Doug Lea’s notes at the top of
ConcurrentHashMap.java(inlib/src.zipof any JDK) — the authoritative design overview
Making the compound action atomic: merge, compute and friends
The fix for the lost update is to hand the whole read-modify-write to the map. For a counter, merge(key, 1, Integer::sum) or compute runs the function while holding the bin’s lock, so no other writer to that bin gets in between the read and the write.
race(id -> { for (int i = 0; i < INCREMENTS_PER_THREAD; i++) m.merge(KEY, 1, Integer::sum); });
race(id -> { for (int i = 0; i < INCREMENTS_PER_THREAD; i++) m.compute(KEY, (k, v) -> v == null ? 1 : v + 1); });
Both lines are in LostUpdateDemo.java (the merge and compute variants). In the measured run the last two variants of 05-measured-lost-updates.txt were exact on all five rounds, as was the plain HashMap with a synchronized (map) block around the pair:
HashMap + synchronized(map) around get+put expected 1,600,000 actual per round: 1,600,000 1,600,000 1,600,000 1,600,000 1,600,000
lost updates per round: min 0, max 0
ConcurrentHashMap merge(KEY, 1, Integer::sum) expected 1,600,000 actual per round: 1,600,000 1,600,000 1,600,000 1,600,000 1,600,000
lost updates per round: min 0, max 0
ConcurrentHashMap compute(KEY, v+1) expected 1,600,000 actual per round: 1,600,000 1,600,000 1,600,000 1,600,000 1,600,000
lost updates per round: min 0, max 0
Those are measured. The test that is allowed to be strict is AtomicUpdatesTest.java, which asserts exact totals on every run (output 08-atomic-updates-exact.txt):
expected: 160000
ConcurrentHashMap.merge 160000
ConcurrentHashMap.compute 160000
HashMap + synchronized(map) around merge 160000
Keep the function short and side-effect free.compute,mergeandcomputeIfAbsentrun your lambda inside the bin lock. A slow lambda blocks every other writer to that bin, and a lambda that touches the same map can fail, as the next section shows.
Going deeper
- AtomicUpdatesTest.java
LongAdderfor pure counters under heavy contention (the concurrency interview hub covers atomics);ConcurrentHashMap<K, LongAdder>is a common pattern
The computeIfAbsent recursion trap (it depends on the bin, not the key)
Memoizing a recursive function with computeIfAbsent is a classic. It breaks differently in each map.
HashMap throws ConcurrentModificationException even single-threaded, because its fail-fast modCount cannot tell “another thread modified me” from “my own recursive call modified me before I finished”. Any structural change made inside the mapping function is detected as a concurrent modification:
$ java ComputeIfAbsentRecursionDemo
=== HashMap: computeIfAbsent recursing into a DIFFERENT key (single-threaded!) ===
threw java.util.ConcurrentModificationException: null
Output and source: 01-computeifabsent-recursion.txt, ComputeIfAbsentRecursionDemo.java. This is a real risk in memoized recursive functions or a “cache of caches” built on a single shared HashMap. The fix is to compute the nested value first into a local variable, then call computeIfAbsent on the outer map with the already-computed value.
ConcurrentHashMap is where the earlier version of this article was too simple. It said recursing into a different key succeeds and recursing into the same key throws IllegalStateException: Recursive update. The JDK 25 source shows the check is about the bin. For an empty bin, computeIfAbsent parks a ReservationNode there, and any recursive call that lands in the same bin finds it and throws. For a non-empty bin it checks pred.next != null after your function returns. The new test uses keys with a chosen hashCode() to control the bin (RecursiveUpdateTest.java, RecursiveUpdateDemo.java). Output from 06-recursive-update.txt:
HashMap, inner key in a different bin: threw java.util.ConcurrentModificationException
ConcurrentHashMap, inner key in a different bin: no exception, size=2
ConcurrentHashMap, inner key, same bin (bin was empty): threw java.lang.IllegalStateException: Recursive update
ConcurrentHashMap, inner key, same bin (bin had a node): threw java.lang.IllegalStateException: Recursive update
So: a recursive call to a different key in a different bin works; a different key in the same bin throws, whether the bin was empty or not. The original demo’s “different key” case worked only because keys 1 and 2 happen to fall in different bins, and the original “same key” case threw because the same key is trivially the same bin. The earlier demo output, still valid for what it shows, is here:
$ java ComputeIfAbsentRecursionDemo
=== ConcurrentHashMap: computeIfAbsent recursing into a DIFFERENT key ===
no exception, result = 99, map = {1=99, 2=99}
=== ConcurrentHashMap: computeIfAbsent recursing into the SAME key ===
threw java.lang.IllegalStateException: Recursive update
The check is documented as “detectably”: the Javadoc promises the exception only for recursive updates that “would otherwise never complete”. Do not build on it; do not recurse into the same map from a mapping function at all. Without the check, the thread would deadlock against a lock it already holds or corrupt the bin.
Nulls: why one map allows them and the other cannot
HashMap allows one null key and any number of null values. ConcurrentHashMap allows neither. The reason is the ambiguity of get(): in a single thread you can follow get(k) == null with containsKey(k) to tell “absent” from “present with null value”. In a concurrent map another thread can change the answer between those two calls, so CHM bans null and lets null mean “no mapping” unambiguously. Run in NullHandlingTest.java, output 07-null-handling.txt:
HashMap.put(null, ..) accepted; the null key lives in table[0]: true
HashMap.get(null) = for-null-key
HashMap.get("present-but-null") = null containsKey = true
HashMap.get("absent") = null containsKey = false <- get() alone cannot tell these two apart
ConcurrentHashMap put(null, v), put(k, null), get(null), containsKey(null), merge(k, null, f): all throw NullPointerException
compute(k, (k,v) -> null) removes the entry instead: containsKey(k) = false
Note the last behaviour: a compute function that returns null removes the entry; it does not store a null. The earlier run, with the exception text from the JDK, shows get(null) failing too (it must call key.hashCode(), same as put), from 02-null-handling.txt and NullHandlingDemo.java:
$ java NullHandlingDemo
=== ConcurrentHashMap: null key throws on put() ===
chm.put(null, "x") threw NullPointerException
=== ConcurrentHashMap: null value throws on put() ===
chm.put("k1", null) threw NullPointerException
=== ConcurrentHashMap: get(null) ALSO throws, not just put() ===
chm.get(null) threw: Cannot invoke "Object.hashCode()" because "key" is null
Going deeper
- NullHandlingTest.java
- Javadoc for
ConcurrentHashMap(null policy and the “weakly consistent” definition) at docs.oracle.com
Real throughput numbers (JMH, JDK 25)
“ConcurrentHashMap scales better” is easy to say and rarely measured. The benchmark below is an 80% get / 20% put workload on Collections.synchronizedMap(new HashMap<>()) versus ConcurrentHashMap, swept across 1, 2, 4 and 8 threads on a 2-vCPU sandbox. These figures were measured earlier on JDK 25.0.4.1+1 with JMH 1.37 (module in the older java-core-examples repository) and were not re-run for this rewrite; expect different absolute numbers on other hardware.
| Threads | synchronizedMap (ops/ms) | ConcurrentHashMap (ops/ms) |
|---|---|---|
| 1 | 33,475 | 46,350 |
| 2 | 8,205 | 47,371 |
| 4 | 9,452 | 46,218 |
| 8 | 7,824 | 43,200 |
Output and source: output/03-06, PutGetBenchmark.java. Two things stand out beyond the headline gap. ConcurrentHashMap was already ahead at one thread, because synchronizedMap pays to enter and exit a monitor on every call while CHM reads (80% of this workload) take no lock. And the gap opens sharply when the second thread appears: one monitor makes every thread, readers included, queue behind whoever holds it, while CHM locks only the bin a write touches. Both numbers flatten past this sandbox’s 2 cores; that is this hardware’s ceiling, not a claim about either map’s limit on server hardware.
Side by side: HashMap vs ConcurrentHashMap
Everything above in one table. Rows marked with an asterisk were corrected or verified against the JDK 25 source and the runs in this article.
| Feature | HashMap | ConcurrentHashMap |
|---|---|---|
| Package | java.util | java.util.concurrent |
| Thread safety | No | Yes, per call (CAS plus a lock on one bin’s head node)* |
| Compound actions (get then put) | Not atomic | Still not atomic; use merge, compute, putIfAbsent* |
| Null key | Allowed (one, stored in bin 0) | Not allowed (NullPointerException) |
| Null value | Allowed | Not allowed |
| Locking | None | Bin-level; reads are lock-free* |
| Default table size | 16 | 16 (DEFAULT_CAPACITY); new CHM(n) sizes for n / 0.75, so 32 gives 64* |
| Default load factor | 0.75 | 0.75 (fixed; the threshold lives in sizeCtl)* |
| Concurrency level | n/a | A sizing hint only in JDK 8+; not a thread limit* |
| Resize trigger | Size exceeds threshold | Count reaches sizeCtl; many threads can help copy* |
| Treeify | 9th node in a bin and table >= 64; otherwise resize | Same constants; root is a TreeBin; the small-table resize can overshoot (16 to 128 observed)* |
size() | Exact field | Sum of baseCount and counter cells; approximate while writers run* |
| Iterator | Fail-fast (ConcurrentModificationException) | Weakly consistent; never throws CME |
computeIfAbsent re-entering the map | ConcurrentModificationException | IllegalStateException: Recursive update if the same bin* |
| Read operations | No synchronization (not safe with concurrent writers) | Lock-free, volatile reads |
| Write operations | No synchronization | CAS on an empty bin, otherwise synchronized on the bin’s head node |
| Performance | Fastest single-threaded; no locking overhead | Scales with threads; slightly slower than HashMap single-threaded in theory, ahead in the JMH run below* |
| Scalability | Poor with shared writers (incorrect, not just slow) | Good, bounded by hash distribution and cores |
| Memory | Lower | Slightly higher (counter cells, forwarding nodes) |
| Use case | Single thread, or externally synchronized | Shared state across threads |
When to use which
Use HashMap when:
- You are working in a single-threaded environment (or the map is built once, safely published, and only read)
- You need maximum performance without concurrency overhead
- You need to store null keys or values
- You manage external synchronization yourself
Use ConcurrentHashMap when:
- You build multi-threaded applications with shared state
- Read operations heavily dominate write operations
- You need atomic operations like
compute()andmerge() - You want to avoid locking the entire data structure
- You need weakly consistent iteration during updates
Use Collections.synchronizedMap mainly for legacy code or when you need one lock around a multi-step operation.
Key takeaways
- Thread safety:
HashMapis not thread-safe;ConcurrentHashMapis safe per call, not per sequence of calls - Performance:
HashMapis faster with one thread and no sharing; CHM scales when threads share the map - Null handling:
HashMapallows null keys and values; CHM prohibits them - Locking strategy: none vs bin-level locking plus CAS (Java 8+)
- Iteration: fail-fast vs weakly consistent
- Memory overhead: CHM has a slightly higher footprint (counter cells, forwarding nodes)
Final advice for interviews: know the API differences, but also the internals: how hashing works, collision handling, resize mechanics, treeification rules, and the evolution from segment locks to bin locks and CAS. Be ready to say what each does under a race, and to show the lost update.
10 interview questions with answers
These answers are the ones the evidence above supports. Each can be said aloud in under a minute.
1. Is ConcurrentHashMap fully thread-safe? Can it still lose updates?
Each individual operation is atomic and visible to other threads, but a sequence of operations is not. m.put(k, m.get(k) + 1) lost updates on a ConcurrentHashMap in the measured run (05) and in the forced test (04). Use merge, compute or putIfAbsent.
2. How does ConcurrentHashMap lock in JDK 25?
It CASes into an empty bin without a lock, helps an in-progress resize when it meets a forwarding node, and otherwise does synchronized on the first node of the bin. Reads take no lock. See excerpt D and the diagram.
3. What is sizeCtl?
One volatile int with state-dependent meaning: 0 or the initial size before the table exists, -1 while one thread allocates it, the next resize threshold (0.75n, e.g. 12 for 16 bins) after, and a negative stamp-based value while a resize runs. Observed values: 0, 12, 24, and 64 then 48 for new ConcurrentHashMap<>(32) (see 02).
4. When does a HashMap bin become a tree?
When a chain already has 8 nodes and a 9th is appended, and the table has at least 64 bins. If the table is smaller, treeifyBin resizes instead. Constants: 8, 6 (untreeify), 64 (read from the JDK in 01). Observed in 03: the tree appears at the 11th colliding insert.
5. Does concurrencyLevel still matter in ConcurrentHashMap?
Not as a thread limit. In JDK 25 it only raises the initial capacity to at least that value; it is not stored. The 16 constant remains for serialization compatibility only.
6. Why does ConcurrentHashMap reject null keys and values?
So that get(k) == null unambiguously means no mapping. With nulls, a caller cannot safely follow get with containsKey because another thread may change the map in between.
7. Why does computeIfAbsent throw ConcurrentModificationException on HashMap and IllegalStateException on ConcurrentHashMap?
HashMap detects that its modCount changed during the call. CHM holds a lock or reservation on the bin and throws Recursive update when the recursive call lands in the same bin. A different bin works. See 06.
8. Why is size() on a ConcurrentHashMap only approximate?
It sums baseCount and a set of counter cells that writers update independently, so there is no single moment of truth while writes continue. Use mappingCount() for large maps; do not use size to make decisions that must be exact under concurrency.
9. synchronizedMap or ConcurrentHashMap?
CHM for shared maps with concurrent reads and writes: in the earlier JMH run it held 43,200 ops/ms at 8 threads against 7,824 for synchronizedMap. synchronizedMap when you need one lock around multi-step operations, nulls, or legacy APIs. Iterating a synchronizedMap still requires manual locking.
10. How do you count word frequencies from many threads?
ConcurrentHashMap<String, Integer> with merge(word, 1, Integer::sum); for extreme contention, ConcurrentHashMap<String, LongAdder> with computeIfAbsent(word, w -> new LongAdder()).increment(). The merge variant was exact on all 5 rounds and in the asserted test (08).
The original question bank (kept and corrected)
The earlier version of this guide was a flat list of questions. They are all still here, grouped into two accordions. Where a statement was wrong or imprecise it has been fixed, and the fix is marked.
HashMap questions (Q1–Q11)
Q1: How does the put() method work internally in HashMap?
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}(From the JDK 25.0.5+8 source, excerpts A and A2.)
Q2: What is the equals() and hashCode() contract in HashMap?
- If two objects are equal according to
equals(), they must have the samehashCode() - If two objects have the same
hashCode(), they are not required to be equal - Violating this makes
HashMapbehave incorrectly
When using custom objects as keys, always override both methods.
Q3: How does HashMap handle collisions?
equals() to find the exact match.Q4: What is the significance of load factor in HashMap?
Q5: Explain the resizing process in HashMap
index + oldCapacity.Q6: Why does HashMap allow null keys and values?
Q7: Can we use mutable objects as keys in HashMap?
hashCode() changes after insertion, the entry becomes unreachable. Use immutable keys such as String and Integer.Q8: What is the difference between HashMap and Hashtable?
Enumerations are not fail-fast, but its Iterator views are.Q9: What is a fail-fast iterator in HashMap?
remove), the iterator throws ConcurrentModificationException. It is a best-effort bug detector, not a concurrency guarantee.Q10: Is HashMap thread-safe? How to make it thread-safe?
Collections.synchronizedMap(new HashMap<>()), ConcurrentHashMap, or external synchronization (not recommended as a default). Corrected: the earlier text also said concurrent use causes infinite loops; that is a Java 7 resize behaviour and was not observed on JDK 25.Q11: What happens if computeIfAbsent recurses back into the same HashMap?
ConcurrentModificationException, even single-threaded, even for a different key. Full explanation and output in the recursion section above.ConcurrentHashMap questions (Q1–Q12)
Q1: How does ConcurrentHashMap achieve better concurrency than Hashtable?
Q2: What is concurrency level in ConcurrentHashMap?
this.concurrencyLevel did not match the real class. The real constructor: public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (initialCapacity < concurrencyLevel) // Use at least as many bins
initialCapacity = concurrencyLevel; // as estimated threads
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}(Excerpt C in the source excerpts file.)
Q3: How does the put() method work in ConcurrentHashMap?
sizeCtl); if the bin is empty, CAS the node in; if the head is a forwarding node, help the resize; otherwise lock the head node, walk the chain or tree, add or replace, then update the count and resize/treeify if needed. See the diagram and excerpt D.Q4: Can multiple threads read from ConcurrentHashMap simultaneously?
Q5: What is the size() method behavior in ConcurrentHashMap?
baseCount and counter cells (excerpt F), not a sum over segments (that was Java 7). The value can be stale while writers run; mappingCount() returns it as a long.Q6: How does ConcurrentHashMap handle null keys and values?
NullPointerException, so null from get always means no mapping. See the nulls section.Q7: What is the performance impact of lock striping?
Q8: How does compute() method work atomically?
race(id -> { for (int i = 0; i < INCREMENTS_PER_THREAD; i++) m.compute(KEY, (k, v) -> v == null ? 1 : v + 1); });Exact total on every run in 08-atomic-updates-exact.txt; the line is in LostUpdateDemo.java.
Q9: What are the iteration characteristics of ConcurrentHashMap?
ConcurrentModificationException, may or may not reflect changes after creation.Q10: When should you use ConcurrentHashMap over Collections.synchronizedMap()?
synchronizedMap for legacy code or when you need strict serialization of access.Q11: What happens if computeIfAbsent recurses back into the same ConcurrentHashMap?
IllegalStateException: Recursive update. Details and output in the recursion section above.Q12: Does get() also reject a null key, or just put()?
get(null) throws NullPointerException too, because it must call key.hashCode(). Output in the nulls section.Should you reach for ConcurrentHashMap by reflex? No. If one thread owns the map,HashMapis simpler and faster. If many threads share it, CHM stops structural corruption but not your logic errors: check-then-act and get-then-put still needmerge,computeorputIfAbsent. And if the real need is a counter, aLongAddermay beat any map. The way to find out is the one this article used: write the racing test and run it.
Further reading
- Companion module: java-interview-lab / hashmap-vs-concurrenthashmap — sizeCtl, treeify, forced and measured lost updates, recursion, nulls (8 captured outputs, 7 tests)
- Older module: java-core-examples / hashmap-concurrenthashmap (recursion demo, null demo, and the JMH benchmark above) and its captured output
- HashMap Internal Working in Java: Hashing, Buckets, Resize and Treeification
- Top 40 Java Concurrency Interview Questions and Answers (2026) — the full concurrency interview hub, including race conditions, deadlocks, and ScopedValue thread inheritance
- JDK 25.0.5+8 source excerpts used in this article (text file)
- ConcurrentHashMap Javadoc (Java 25)
- HashMap Javadoc (Java 25)
No Comments yet!