ConcurrentHashMap basics
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Many threads update the same map of product stock at once. A plain HashMap can lose updates or break, and locking the whole map makes every thread wait in a line. Is there a better map?
put and get from many threads
ConcurrentHashMap is a thread-safe map that lets many threads read and update it at the same time without locking the whole map.
ConcurrentHashMap<K, V> implements the normal Map interface, so put, get, remove, containsKey and getOrDefault work exactly as with HashMap. The difference is that every one of these calls is safe when many threads make them at the same time.
Example 1 · An exam result server with 8 threads
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
public class ResultServerDemo { public static void main(String[] args) throws InterruptedException { Map<Integer, String> results = new ConcurrentHashMap<>(); List<Thread> threads = new ArrayList<>();
for (int s = 0; s < 4; s++) { // 4 writer threads int first = s * 25_000; Thread t = new Thread(() -> { for (int roll = first; roll < first + 25_000; roll++) { results.put(roll, roll % 10 == 0 ? "FAIL" : "PASS"); } }, "writer-" + (s + 1)); threads.add(t); t.start(); } for (Thread t : threads) { t.join(); } System.out.println("Results stored: " + results.size());
AtomicInteger failCount = new AtomicInteger(); threads.clear(); for (int s = 0; s < 4; s++) { // 4 reader threads at the same time int first = s * 25_000; Thread t = new Thread(() -> { for (int roll = first; roll < first + 25_000; roll++) { if (results.get(roll).equals("FAIL")) { failCount.incrementAndGet(); } } }, "reader-" + (s + 1)); threads.add(t); t.start(); } for (Thread t : threads) { t.join(); } System.out.println("Students who failed: " + failCount.get()); System.out.println("Roll 4321: " + results.get(4321)); }}Results stored: 100000 Students who failed: 10000 Roll 4321: PASS
What this code does
- Four writer threads store 100,000 results and then four reader threads look them up, with no locks in our code. Every result is kept, unlike the
HashMapversion in the first lesson of this module. failCountis anAtomicInteger, because the readers share that counter too. The map makes map calls safe; it does not protect other shared variables.
Example 2 · A long report no longer blocks a lookup
import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
public class NoWaitReadDemo { static volatile boolean reportStarted = false;
public static void main(String[] args) throws InterruptedException { Map<String, Integer> balances = new ConcurrentHashMap<>(); balances.put("asha@upi", 1200); balances.put("ravi@upi", 300);
Thread report = new Thread(() -> { for (String id : balances.keySet()) { // a long loop, but no map-wide lock reportStarted = true; sleepMillis(100); // pretend each line takes time } }, "night-report"); report.start(); while (!reportStarted) { sleepMillis(5); // wait until the report is running }
long start = System.nanoTime(); int balance = balances.get("ravi@upi"); long waitedMs = (System.nanoTime() - start) / 1_000_000; report.join();
System.out.println("ravi@upi balance: " + balance); System.out.println("get() had to wait for the report: " + (waitedMs >= 100)); }
static void sleepMillis(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}ravi@upi balance: 300 get() had to wait for the report: false
What this code does
- The night report loops slowly over the keys, but looping does not lock the map.
maingets the balance at once instead of waiting about 200 ms. - Compare this with the synchronized map in the previous lesson, where the same program printed
true.
It does not use one lock for the whole map. A get takes no lock at all, and a put locks only the small part of the map where its key lives, so threads working on different keys rarely wait for each other. The lesson "How ConcurrentHashMap works inside" shows how. In Example 2, the same slow night report that blocked get on a synchronized map in the last lesson now runs without stopping anyone: the lookup returns at once.
No null keys or values, and why
ConcurrentHashMap does not allow null as a key or as a value. put(null, v) and put(k, null) both throw NullPointerException.
Example 3 · No nulls: use a sentinel or a default
import java.util.HashMap;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
public class NoNullsDemo { public static void main(String[] args) { Map<String, String> plain = new HashMap<>(); plain.put("Neha", null); // HashMap allows a null value System.out.println("HashMap get(Neha): " + plain.get("Neha") + ", containsKey: " + plain.containsKey("Neha"));
Map<String, String> rooms = new ConcurrentHashMap<>(); try { rooms.put("Neha", null); } catch (NullPointerException e) { System.out.println("null value: NullPointerException"); } try { rooms.put(null, "B-12"); } catch (NullPointerException e) { System.out.println("null key: NullPointerException"); }
rooms.put("Neha", "NOT_ALLOTTED"); // a sentinel value instead of null rooms.put("Imran", "B-12"); System.out.println("Neha: " + rooms.get("Neha")); System.out.println("Imran: " + rooms.get("Imran")); System.out.println("Zoya: " + rooms.get("Zoya")); // null can only mean "no such key" System.out.println("Zoya with default: " + rooms.getOrDefault("Zoya", "UNKNOWN")); }}HashMap get(Neha): null, containsKey: true null value: NullPointerException null key: NullPointerException Neha: NOT_ALLOTTED Imran: B-12 Zoya: null Zoya with default: UNKNOWN
What this code does
HashMapstores anullvalue, sogetreturnsnulleven though the key exists.ConcurrentHashMaprejects both anullvalue and anullkey withNullPointerException.NOT_ALLOTTEDmarks a known student with no room yet. Nownullfromget("Zoya")can only mean "not in the map", andgetOrDefaultreplaces it with a readable default.
The reason is that get returns null to mean "no such key". In a HashMap that also allows null values, you can tell the two cases apart by calling containsKey next. In a map shared by threads, another thread can add or remove the key between your get and your containsKey, so the second answer may not match the first. By banning null, a null result from get always means one thing: the key is absent. When you need "known, but no value yet", store a sentinel: a special value you choose, such as the string "NOT_ALLOTTED". For lookups of keys that may be missing, getOrDefault(key, fallback) reads well.
Weakly consistent iteration
Iterators of ConcurrentHashMap are weakly consistent: they never throw ConcurrentModificationException, they visit every entry that existed when the loop started (unless it is removed first) exactly once, and they may or may not show changes made while the loop runs.
Example 4 · Changing the map inside a loop
import java.util.Map;import java.util.TreeMap;import java.util.concurrent.ConcurrentHashMap;
public class RemoveWhileLoopingDemo { public static void main(String[] args) { Map<String, Integer> dues = new ConcurrentHashMap<>(); dues.put("Asha", 0); dues.put("Bala", 4500); dues.put("Chirag", 0); dues.put("Divya", 1200);
for (String name : dues.keySet()) { if (dues.get(name) == 0) { dues.remove(name); // no ConcurrentModificationException } } System.out.println("Still owe fees: " + new TreeMap<>(dues));
for (String name : dues.keySet()) { if (name.equals("Bala")) { dues.put("Esha", 800); // added during the loop } } System.out.println("Adding during the loop: no exception either"); System.out.println("Final map: " + new TreeMap<>(dues)); }}Still owe fees: {Bala=4500, Divya=1200}
Adding during the loop: no exception either
Final map: {Bala=4500, Divya=1200, Esha=800}What this code does
- Removing paid students inside a for-each loop would throw a CME on a
HashMap. Here the weakly consistent iterator simply carries on. Eshais added during the second loop. Whether that same loop visits her depends on where her key lands inside the map, so code must not depend on it. After the loop she is certainly in the map.
Example 5 · One thread loops while another adds
import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
public class WeakIteratorDemo { public static void main(String[] args) throws InterruptedException { Map<Integer, Integer> marks = new ConcurrentHashMap<>(); for (int roll = 0; roll < 1_000; roll++) { marks.put(roll, 70); }
int[] seen = new int[1]; Thread reader = new Thread(() -> { for (int roll : marks.keySet()) { // loop while the writer adds seen[0]++; } }, "report-reader");
Thread writer = new Thread(() -> { for (int roll = 1_000; roll < 101_000; roll++) { marks.put(roll, 85); } }, "marks-writer");
reader.start(); writer.start(); reader.join(); writer.join();
System.out.println("Reader finished with no ConcurrentModificationException"); System.out.println("Reader saw at least the first 1000 entries: " + (seen[0] >= 1_000)); System.out.println("Reader saw at most all 101000 entries: " + (seen[0] <= 101_000)); System.out.println("Final size after join: " + marks.size()); }}Reader finished with no ConcurrentModificationException Reader saw at least the first 1000 entries: true Reader saw at most all 101000 entries: true Final size after join: 101000
What this code does
- The reader loops while the writer adds 100,000 entries. There is no exception, and the reader sees at least the 1,000 entries that existed at the start.
- How many of the new entries the reader sees changes from run to run, which is why the program prints only the guaranteed facts. After
join(), the size is exact.
So you can remove entries inside a for-each loop over the map, even in a single thread (Example 4), and one thread can loop while others add and remove (Example 5). The loop never crashes and never visits a key twice. The price is that the loop is not a snapshot (a picture of the whole map at one moment). A total computed while other threads are writing may include some new entries and miss others. If you need the exact final data, wait for the writers first, for example with join().
Predict the output
Which loops survive a change?
Read each program and pick what it prints.
Round 1 of 2
A ConcurrentHashMap, with an item removed inside the loop.
size() is only an estimate under change
size() on a ConcurrentHashMap adds up internal counters without locking the map. While other threads are adding or removing, the number may already be out of date by the time you read it. The Java docs call it an estimate.
Example 6 · size() while writers are busy
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;
public class SizeEstimateDemo { public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<Integer, String> orders = new ConcurrentHashMap<>(); List<Thread> writers = new ArrayList<>(); for (int w = 0; w < 4; w++) { int first = w * 250_000; Thread t = new Thread(() -> { for (int id = first; id < first + 250_000; id++) { orders.put(id, "PLACED"); } }, "app-server-" + (w + 1)); writers.add(t); }
for (Thread t : writers) { t.start(); } for (int i = 1; i <= 3; i++) { Thread.sleep(20); System.out.println("size() while writing: " + orders.size()); } for (Thread t : writers) { t.join(); } System.out.println("size() after join: " + orders.size()); System.out.println("mappingCount(): " + orders.mappingCount()); }}size() while writing: 122979 size() while writing: 208435 size() while writing: 298231 size() after join: 1000000 mappingCount(): 1000000
What this code does
- While four threads add a million orders,
size()gives a different moving number each time. The three middle numbers change on every run. - After
join()no thread is writing, sosize()andmappingCount()are exact.
Once all writers have finished, it is exact.
mappingCount() does the same job but returns a long, so it also works for maps with more than about 2.1 billion entries. The Java docs suggest it over size().
- Fine: showing "about 2,08,435 orders so far" on a dashboard.
- Wrong:
if (map.size() < 100) map.put(...)to enforce a limit. The check and theputare two steps, and other threads can fill the map in between. isEmpty()has the same limit: it is a hint, not a promise.
Next step
Check your understanding
12 quick questions