ConcurrentHashMap
ConcurrentHashMap is the thread-safe hash map most concurrent Java code uses. It lets many threads read and write at once without one global lock, but individual calls being safe does not make sequences of calls safe. This page explains how it works inside, shows lost updates and the atomic methods that prevent them, covers bulk operations and the traps in compute, and measures throughput.
Contents
How ConcurrentHashMap works
A HashMapHashtableCollections.synchronizedMap
ConcurrentHashMapHashMapHashMap
The Java 5 version worked differently: it split the map into 16 segments by default, each a small hash table with its own lock, so at most 16 writers could proceed at once. Java 8 removed the segments in favour of per-bin locking. The concurrencyLevelLongAddersize()
Two rules follow from this design. Each single method call is atomic, but a sequence such as getputnullgetnull
| Map | Since | Locking | Best for |
|---|---|---|---|
Hashtable | Java 1.0 | Every method synchronized on the map | Legacy code only |
Collections.synchronizedMap | Java 1.2 | One lock for the whole map | Low-contention code that already uses HashMap |
ConcurrentHashMap | Java 5, redesigned in Java 8 | Lock-free reads; per-bin locks for writes | Shared caches, counters, registries |
ConcurrentSkipListMap | Java 6 | Lock-free skip list | Concurrent sorted maps |
The programs on this page were run on JDK 21; results of the multi-threaded ones vary between runs.
Lost updates: thread-safe calls are not enough
Eight threads each count 100,000 hits on the same key in three maps: a HashMapConcurrentHashMapgetputConcurrentHashMapmerge
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class LostUpdates {
static final int THREADS = 8;
static final int INCREMENTS = 100000;
public static void main(String[] args) throws InterruptedException {
Map<String, Integer> plain = new HashMap<>();
Map<String, Integer> concurrentButWrong = new ConcurrentHashMap<>();
ConcurrentHashMap<String, Integer> atomic = new ConcurrentHashMap<>();
ExecutorService pool = Executors.newFixedThreadPool(THREADS);
for (int t = 0; t < THREADS; t++) {
pool.submit(() -> {
for (int i = 0; i < INCREMENTS; i++) {
synchronized (plain) { // HashMap needs an external lock
plain.put("hits", plain.getOrDefault("hits", 0) + 1);
}
// get then put: two separate calls, another thread can run in between
Integer old = concurrentButWrong.getOrDefault("hits", 0);
concurrentButWrong.put("hits", old + 1);
// merge: one atomic read-modify-write
atomic.merge("hits", 1, Integer::sum);
}
});
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("expected: " + THREADS * INCREMENTS);
System.out.println("HashMap + synchronized: " + plain.get("hits"));
System.out.println("CHM get + put: " + concurrentButWrong.get("hits"));
System.out.println("CHM merge: " + atomic.get("hits"));
}
}
Output (the middle number changes from run to run):
expected: 800000
HashMap + synchronized: 800000
CHM get + put: 567434
CHM merge: 800000
- The locked
and theHashMap version both reached the expected 800,000.merge - The
-then-get version lost a large share of the increments. Two threads read the same old value, both add one, and both write back the same result. The map itself was never corrupted; the program's logic was.put performs the read, the update and the write as one atomic operation on that key. Any read-modify-write on a shared map must use one of the atomic methods.merge- The same reasoning applies to checks such as
: another thread can insert between the two calls.if (!map.containsKey(k)) map.put(k, v) does both in one step.putIfAbsent
The atomic methods
Each method below does a check and an update as one step. The stock example walks through them in order, ending with a multimap and the null rule.
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
public class AtomicMethods {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>();
// putIfAbsent: insert only when no value is present
stock.putIfAbsent("apple", 10);
stock.putIfAbsent("apple", 99); // ignored, apple already present
System.out.println("putIfAbsent: " + stock);
// compute: replace the value using the old one (old is null when absent)
stock.compute("apple", (key, old) -> old == null ? 1 : old - 3);
System.out.println("compute: " + stock);
// computeIfPresent returning null removes the entry
stock.computeIfPresent("apple", (key, old) -> old <= 7 ? null : old);
System.out.println("removed at 7: " + stock);
// replace(key, expected, new) is a compare-and-set on the value
stock.put("pear", 5);
System.out.println("replace 5->6: " + stock.replace("pear", 5, 6));
System.out.println("replace 5->7: " + stock.replace("pear", 5, 7) + " " + stock);
// computeIfAbsent: build a value once per key, e.g. a multimap
ConcurrentHashMap<String, List<String>> byLetter = new ConcurrentHashMap<>();
for (String w : List.of("ant", "bee", "asp", "bat", "cow")) {
byLetter.computeIfAbsent(w.substring(0, 1), k -> new ArrayList<>()).add(w);
}
System.out.println("multimap: " + new TreeMap<>(byLetter));
// No null keys or values: null would be ambiguous with "absent"
try {
stock.put("plum", null);
} catch (NullPointerException e) {
System.out.println("put null: NullPointerException");
}
}
}
Output:
putIfAbsent: {apple=10}
compute: {apple=7}
removed at 7: {}
replace 5->6: true
replace 5->7: false {pear=6}
multimap: {a=[ant, asp], b=[bee, bat], c=[cow]}
put null: NullPointerException
inserts only when the key has no value, so the second call with 99 was ignored.putIfAbsent receives the old value, orcompute when absent, and stores whatever it returns. Returningnull fromnull orcompute removes the entry, which is how the apple at 7 disappeared.computeIfPresent is a compare-and-set: the first call succeeded because the value was 5, the second failed because it had become 6.replace(key, expected, newValue) creates a value once per key, the usual way to build a multimap. ThecomputeIfAbsent on the returnedadd happens outside the map's lock, though, so with several threads the lists themselves must be thread-safe, or the add must happen insideArrayList .compute throwsput(key, null) .NullPointerException
Iteration and bulk operations
ConcurrentHashMap
import java.util.concurrent.ConcurrentHashMap;
public class BulkAndIteration {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> sales = new ConcurrentHashMap<>();
sales.put("north", 120);
sales.put("south", 75);
sales.put("east", 210);
sales.put("west", 40);
// Iterating while modifying is allowed: no ConcurrentModificationException
for (String region : sales.keySet()) {
if (sales.get(region) < 50) {
sales.remove(region);
}
}
System.out.println("after removing < 50: " + sales.size() + " regions");
// Bulk operations take a parallelism threshold:
// Long.MAX_VALUE = run on this thread, 1 = use the common pool when worthwhile
long total = sales.reduceValuesToLong(Long.MAX_VALUE, Integer::longValue, 0L, Long::sum);
System.out.println("total: " + total);
String best = sales.reduceEntries(Long.MAX_VALUE,
(a, b) -> a.getValue() >= b.getValue() ? a : b).getKey();
System.out.println("best region: " + best);
String firstBig = sales.search(Long.MAX_VALUE, (k, v) -> v > 100 ? k : null);
System.out.println("some region > 100: " + (firstBig != null));
// mappingCount returns a long; size() is capped at Integer.MAX_VALUE
System.out.println("mappingCount: " + sales.mappingCount());
// A concurrent Set backed by a ConcurrentHashMap
var seen = ConcurrentHashMap.<String>newKeySet();
seen.add("id-1");
System.out.println("newKeySet add again: " + seen.add("id-1"));
}
}
Output:
after removing < 50: 3 regions
total: 405
best region: east
some region > 100: true
mappingCount: 3
newKeySet add again: false
- Removing entries while iterating is allowed and throws no
. The iterators are weakly consistent: they reflect the map at some point during the iteration and may or may not show changes made meanwhile.ConcurrentModificationException andreduceValuesToLong combine all entries;reduceEntries returns the first non-null result of a function. The first argument is the parallelism threshold:search runs on the calling thread, while a small number lets large maps use the commonLong.MAX_VALUE .ForkJoinPool- Because the order of entries is unspecified,
may find any matching entry. Results of a reduction should not depend on order.search returns amappingCount() ;long is capped atsize() . With concurrent writers, both are estimates at that moment.Integer.MAX_VALUE returns a thread-safeConcurrentHashMap.newKeySet() backed by the map.Set
Traps inside compute
The function passed to computecomputeIfAbsentmergeHashMap
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
public class ComputeTraps {
static final ConcurrentHashMap<Integer, Long> FIB = new ConcurrentHashMap<>();
// Memoized Fibonacci that calls computeIfAbsent recursively: not allowed
static long fib(int n) {
if (n < 2) {
return n;
}
return FIB.computeIfAbsent(n, k -> fib(k - 1) + fib(k - 2));
}
public static void main(String[] args) throws InterruptedException {
try {
System.out.println("fib(30) = " + fib(30));
} catch (IllegalStateException e) {
System.out.println("recursive computeIfAbsent: IllegalStateException: "
+ e.getMessage());
}
// A slow function inside compute blocks other writers of the same bin
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 0);
CountDownLatch started = new CountDownLatch(1);
Thread slow = new Thread(() -> map.compute("key", (k, v) -> {
started.countDown();
sleep(300); // e.g. a remote call: do not do this
return v + 1;
}));
slow.start();
started.await();
long t0 = System.nanoTime();
map.merge("key", 10, Integer::sum); // has to wait for the compute
System.out.printf("merge on the same key waited %.0f ms; value now %d%n",
(System.nanoTime() - t0) / 1e6, map.get("key"));
slow.join();
// Iterators are weakly consistent: modifying while iterating is allowed
Map<String, Integer> chm = new ConcurrentHashMap<>(Map.of("a", 1, "b", 2, "c", 3));
for (String k : chm.keySet()) {
chm.put(k + k, 0); // may or may not be seen by this loop
}
System.out.println("CHM after adding during iteration: " + chm.size() + " entries");
Map<String, Integer> hash = new HashMap<>(Map.of("a", 1, "b", 2, "c", 3));
try {
for (String k : hash.keySet()) {
hash.put(k + k, 0);
}
} catch (ConcurrentModificationException e) {
System.out.println("HashMap during iteration: ConcurrentModificationException");
}
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Output:
recursive computeIfAbsent: IllegalStateException: Recursive update
merge on the same key waited 300 ms; value now 11
CHM after adding during iteration: 6 entries
HashMap during iteration: ConcurrentModificationException
- Memoizing a recursive function with
modifies the map from inside its own mapping function.computeIfAbsent detects this and throwsConcurrentHashMap with "Recursive update"; in other cases it can deadlock. Compute such values outside the map and insert the result.IllegalStateException - While one thread's
slept for 300 ms, acompute on the same key waited the full 300 ms. Keep these functions short and never do I/O or remote calls inside them.merge - Adding keys while iterating a
is allowed, and whether the loop sees the new keys is unspecified. The same loop on aConcurrentHashMap threwHashMap .ConcurrentModificationException
Throughput compared
Four threads increment counters for 64 keys, half a million times each, in four kinds of map, keeping the fastest of three runs.
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
public class Throughput {
static final int THREADS = 4;
static final int OPS = 500000;
static final String[] KEYS = new String[64];
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < KEYS.length; i++) {
KEYS[i] = "k" + i;
}
System.out.printf("%d threads x %,d increments over %d keys%n", THREADS, OPS, KEYS.length);
Map<String, Integer> table = new Hashtable<>();
run("Hashtable.merge", i -> table.merge(KEYS[i & 63], 1, Integer::sum), table::clear);
Map<String, Integer> sync = Collections.synchronizedMap(new HashMap<>());
run("synchronizedMap.merge", i -> sync.merge(KEYS[i & 63], 1, Integer::sum), sync::clear);
ConcurrentHashMap<String, Integer> chm = new ConcurrentHashMap<>();
run("ConcurrentHashMap.merge", i -> chm.merge(KEYS[i & 63], 1, Integer::sum), chm::clear);
ConcurrentHashMap<String, LongAdder> adders = new ConcurrentHashMap<>();
run("CHM + LongAdder", i -> adders.computeIfAbsent(KEYS[i & 63], k -> new LongAdder())
.increment(), adders::clear);
long total = adders.values().stream().mapToLong(LongAdder::sum).sum();
System.out.println("LongAdder total after the last run: " + total);
}
static void run(String name, Consumer<Integer> op, Runnable reset)
throws InterruptedException {
long best = Long.MAX_VALUE;
for (int r = 0; r < 3; r++) {
reset.run();
Thread[] threads = new Thread[THREADS];
long t0 = System.nanoTime();
for (int t = 0; t < THREADS; t++) {
int seed = t;
threads[t] = new Thread(() -> {
for (int i = 0; i < OPS; i++) {
op.accept(i * 31 + seed);
}
});
threads[t].start();
}
for (Thread th : threads) {
th.join();
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-26s %7.1f ms%n", name, best / 1e6);
}
}
Output (rough timings on a 2-CPU Linux machine, JDK 21; on more cores the gaps widen):
4 threads x 500,000 increments over 64 keys
Hashtable.merge 132.4 ms
synchronizedMap.merge 193.1 ms
ConcurrentHashMap.merge 84.5 ms
CHM + LongAdder 21.9 ms
LongAdder total after the last run: 2000000
andHashtable were the two slowest, and which of them came last changed between runs. Both take one lock for the whole map on every call, so all four threads queue for it. With only two CPUs contention is limited; the cost of a single lock grows with the number of cores.synchronizedMap was faster still, because threads updating different keys lock different bins.ConcurrentHashMap.merge- Storing a
per key and callingLongAdder was the fastest. After the first call,increment() only reads, andcomputeIfAbsent spreads the counting across cells to avoid contention on one value. The total was exactly 2,000,000.LongAdder
When to use ConcurrentHashMap
| Situation | Use |
|---|---|
| Map shared between threads | ConcurrentHashMap |
| Read, change and write a value | mergecomputecomputeIfAbsentgetput |
| High-frequency counters | ConcurrentHashMap<K, LongAdder> |
| Insert only if missing | putIfAbsentcomputeIfAbsent |
| Thread-safe set | ConcurrentHashMap.newKeySet() |
| Sorted keys, concurrently | ConcurrentSkipListMap |
| Values computed by slow or recursive code | Compute outside the map, then putIfAbsent |
| Mostly reads, rare writes, small map | An immutable map replaced on change, or ConcurrentHashMap |
| Map used by one thread only | HashMap |
How the underlying hash table works is explained on the