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 HashMap is not safe for concurrent use: two threads writing at the same time can lose entries or corrupt the table. The old fixes, Hashtable and Collections.synchronizedMap, put one lock around the whole map, so only one thread at a time can use it at all.

ConcurrentHashMap, added in Java 5 and rewritten in Java 8, locks much less. Its table is an array of bins, as in HashMap. Reading never locks: it uses volatile reads of the bins. Writing to an empty bin uses a single compare-and-set instruction. Writing to a bin that already has entries locks only that bin's first node, so threads that write to different bins do not wait for each other. A bin with many collisions turns into a small tree, as in HashMap, and the table grows with several threads helping to move the entries.

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 concurrencyLevel constructor argument survives, but the documentation now describes it only as a sizing hint. The element count is kept in a set of counter cells, similar to LongAdder, so that size() does not become a point of contention, at the price of being an estimate while writers are active.

Two rules follow from this design. Each single method call is atomic, but a sequence such as get followed by put is not. And the map rejects null keys and values, because get returning null must unambiguously mean "absent" when other threads may change the map in between.

Thread-safe maps
MapSinceLockingBest for
HashtableJava 1.0Every method synchronized on the mapLegacy code only
Collections.synchronizedMapJava 1.2One lock for the whole mapLow-contention code that already uses HashMap
ConcurrentHashMapJava 5, redesigned in Java 8Lock-free reads; per-bin locks for writesShared caches, counters, registries
ConcurrentSkipListMapJava 6Lock-free skip listConcurrent 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 HashMap with an external lock, a ConcurrentHashMap updated with get then put, and a ConcurrentHashMap updated with merge.

Java
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):

Output
expected:                800000
HashMap + synchronized:  800000
CHM get + put:           567434
CHM merge:               800000
  • The locked HashMap and the merge version both reached the expected 800,000.
  • The get-then-put 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.
  • merge 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.
  • The same reasoning applies to checks such as if (!map.containsKey(k)) map.put(k, v): another thread can insert between the two calls. putIfAbsent does both in one step.

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.

Java
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:

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
  • putIfAbsent inserts only when the key has no value, so the second call with 99 was ignored.
  • compute receives the old value, or null when absent, and stores whatever it returns. Returning null from compute or computeIfPresent removes the entry, which is how the apple at 7 disappeared.
  • replace(key, expected, newValue) is a compare-and-set: the first call succeeded because the value was 5, the second failed because it had become 6.
  • computeIfAbsent creates a value once per key, the usual way to build a multimap. The add on the returned ArrayList happens outside the map's lock, though, so with several threads the lists themselves must be thread-safe, or the add must happen inside compute.
  • put(key, null) throws NullPointerException.

Iteration and bulk operations

ConcurrentHashMap has its own bulk methods for searching, reducing and visiting entries, with an optional parallelism threshold. The sales map is small so the results can be checked by hand.

Java
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:

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 ConcurrentModificationException. The iterators are weakly consistent: they reflect the map at some point during the iteration and may or may not show changes made meanwhile.
  • reduceValuesToLong and reduceEntries combine all entries; search returns the first non-null result of a function. The first argument is the parallelism threshold: Long.MAX_VALUE runs on the calling thread, while a small number lets large maps use the common ForkJoinPool.
  • Because the order of entries is unspecified, search may find any matching entry. Results of a reduction should not depend on order.
  • mappingCount() returns a long; size() is capped at Integer.MAX_VALUE. With concurrent writers, both are estimates at that moment.
  • ConcurrentHashMap.newKeySet() returns a thread-safe Set backed by the map.

Traps inside compute

The function passed to compute, computeIfAbsent or merge runs while the bin is locked. The program shows what happens when that function calls back into the map, when it is slow, and how iteration differs from HashMap.

Java
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:

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 computeIfAbsent modifies the map from inside its own mapping function. ConcurrentHashMap detects this and throws IllegalStateException with "Recursive update"; in other cases it can deadlock. Compute such values outside the map and insert the result.
  • While one thread's compute slept for 300 ms, a merge on the same key waited the full 300 ms. Keep these functions short and never do I/O or remote calls inside them.
  • Adding keys while iterating a ConcurrentHashMap is allowed, and whether the loop sees the new keys is unspecified. The same loop on a HashMap threw 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.

Java
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):

Output
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
  • Hashtable and synchronizedMap 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.
  • ConcurrentHashMap.merge was faster still, because threads updating different keys lock different bins.
  • Storing a LongAdder per key and calling increment() was the fastest. After the first call, computeIfAbsent only reads, and LongAdder spreads the counting across cells to avoid contention on one value. The total was exactly 2,000,000.

When to use ConcurrentHashMap

Choosing a concurrent map approach
SituationUse
Map shared between threadsConcurrentHashMap
Read, change and write a valuemerge, compute, computeIfAbsent, never get then put
High-frequency countersConcurrentHashMap<K, LongAdder>
Insert only if missingputIfAbsent or computeIfAbsent
Thread-safe setConcurrentHashMap.newKeySet()
Sorted keys, concurrentlyConcurrentSkipListMap
Values computed by slow or recursive codeCompute outside the map, then putIfAbsent
Mostly reads, rare writes, small mapAn immutable map replaced on change, or ConcurrentHashMap
Map used by one thread onlyHashMap

How the underlying hash table works is explained on the HashMap internals page, and other concurrent collections on the copy-on-write and concurrent collections page.