ConcurrentHashMap atomic methods
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ConcurrentHashMap makes each single call safe, but most real updates need two steps: read the old value, then write a new one. The map's atomic methods (putIfAbsent, computeIfAbsent, merge, compute and computeIfPresent) do the read and the write as one step, so no other thread can slip in between.
putIfAbsent and computeIfAbsent
An atomic operation is a step that other threads can never see half done. putIfAbsent, computeIfAbsent, merge and compute each read and change one entry as a single atomic step.
putIfAbsent(key, value) stores the value only if the key is not in the map yet, and does it in one atomic step. It returns null when it stored your value, or the value that was already there.
Example 1 · putIfAbsent: only one phone gets each username
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
public class ClaimUsernamesDemo { public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<String, String> usernames = new ConcurrentHashMap<>(); AtomicInteger wins = new AtomicInteger(); List<Thread> phones = new ArrayList<>();
for (int p = 1; p <= 4; p++) { String phone = "phone-" + p; Thread t = new Thread(() -> { for (int i = 1; i <= 1_000; i++) { String name = "student" + i; // stores phone only if nobody has the name; returns the old owner or null if (usernames.putIfAbsent(name, phone) == null) { wins.incrementAndGet(); } } }, phone); phones.add(t); t.start(); } for (Thread t : phones) { t.join(); }
System.out.println("Usernames taken: " + usernames.size()); System.out.println("Successful claims: " + wins.get());
String owner = usernames.get("student7"); String result = usernames.putIfAbsent("student7", "phone-99"); System.out.println("Late claim for student7 returned the owner: " + result.equals(owner)); }}Usernames taken: 1000 Successful claims: 1000 Late claim for student7 returned the owner: true
What this code does
- Four phones try to claim the same 1,000 usernames at the same time.
putIfAbsentreturnsnullonly for the one thread that stored its value, so exactly 1,000 claims succeed on every run. - A later
putIfAbsenton a taken name changes nothing and returns the current owner. Which phone owns which name changes from run to run, so the program prints only the guaranteed facts.
Example 2 · computeIfAbsent: a cache that loads each profile once
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
public class ProfileCacheDemo { static final ConcurrentHashMap<Integer, String> cache = new ConcurrentHashMap<>(); static final AtomicInteger databaseCalls = new AtomicInteger();
static String loadFromDatabase(int roll) { databaseCalls.incrementAndGet(); // pretend this is a slow query return "Student-" + roll; }
static String profile(int roll) { // runs loadFromDatabase only if roll is not cached yet, and stores the result return cache.computeIfAbsent(roll, r -> loadFromDatabase(r)); }
public static void main(String[] args) throws InterruptedException { List<Thread> servers = new ArrayList<>(); for (int s = 1; s <= 4; s++) { Thread t = new Thread(() -> { for (int i = 0; i < 1_000; i++) { profile(1 + i % 3); // everyone asks for rolls 1, 2 and 3 } }, "web-" + s); servers.add(t); t.start(); } for (Thread t : servers) { t.join(); }
System.out.println("Lookups: 4000"); System.out.println("Database calls: " + databaseCalls.get()); System.out.println("Roll 2 -> " + profile(2)); }}Lookups: 4000 Database calls: 3 Roll 2 -> Student-2
What this code does
- Four web threads make 4,000 lookups for three roll numbers. The slow loader runs only 3 times: once per key, even when threads ask for a new key at the same moment.
computeIfAbsentreturns the cached value or the newly built one, soprofileneeds noif. A lambda liker -> loadFromDatabase(r)could also be writtenProfileCacheDemo::loadFromDatabase.
So if (map.putIfAbsent(name, me) == null) means "I got it", and exactly one thread can win each key (Example 1).
computeIfAbsent(key, k -> makeValue(k)) is the lazy version: the function runs only when the key is missing, and its result is stored and returned. If the key exists, you get the existing value and the function never runs. ConcurrentHashMap promises the function runs at most once per key, even when many threads ask at the same time, which makes it ideal for a cache (Example 2).
A common use is grouping: map.computeIfAbsent(club, c -> ConcurrentHashMap.newKeySet()).add(name). The map call is atomic, but the add happens afterwards on the inner collection, so the inner collection must be thread-safe too.
IllegalStateException: Recursive update or hang).merge for counting words
merge(key, value, fn) stores value if the key is absent; otherwise it stores fn(oldValue, value). All of it happens as one atomic step. If fn returns null, the entry is removed.
Example 3 · merge: counting words from fest feedback
import java.util.ArrayList;import java.util.List;import java.util.TreeMap;import java.util.concurrent.ConcurrentHashMap;
public class WordCountDemo { public static void main(String[] args) throws InterruptedException { String[] feedback = { "good fest good venue", "venue was late", "good music late night", "music good venue good" }; ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
List<Thread> readers = new ArrayList<>(); for (int f = 0; f < feedback.length; f++) { String line = feedback[f]; Thread t = new Thread(() -> { for (int repeat = 0; repeat < 1_000; repeat++) { // each form was sent 1000 times for (String word : line.split(" ")) { counts.merge(word, 1, Integer::sum); // 1 if new, else old + 1 } } }, "form-reader-" + (f + 1)); readers.add(t); t.start(); } for (Thread t : readers) { t.join(); } System.out.println(new TreeMap<>(counts)); }}{fest=1000, good=5000, late=2000, music=2000, night=1000, venue=3000, was=1000}What this code does
- Four threads count words from feedback forms into one map with
merge(word, 1, Integer::sum). Every count is exact, and the result is the same on every run. new TreeMap<>(counts)copies the finished map into a sorted map, only for printing in alphabetical order.
This makes counting a one-liner: counts.merge(word, 1, Integer::sum). The first time a word appears it gets 1; every later time, Integer.sum(old, 1) adds one. Summing amounts works the same way: totals.merge(merchant, amount, Integer::sum). merge is the usual answer whenever you would otherwise write "get the old count, add, put it back".
compute and computeIfPresent
compute(key, (k, old) -> newValue) runs your function with the current value (old is null if the key is absent) and stores what it returns, as one atomic step. Returning null removes the entry.
Example 4 · compute: keeping the top mark per subject
import java.util.ArrayList;import java.util.List;import java.util.TreeMap;import java.util.concurrent.ConcurrentHashMap;
public class ToppersDemo { public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<String, Integer> topMark = new ConcurrentHashMap<>(); String[][] halls = { {"Maths:88", "Physics:71", "Chemistry:90"}, {"Maths:97", "Physics:84"}, {"Physics:79", "Chemistry:93", "Maths:91"} };
List<Thread> threads = new ArrayList<>(); for (int h = 0; h < halls.length; h++) { String[] sheets = halls[h]; Thread t = new Thread(() -> { for (String sheet : sheets) { String subject = sheet.split(":")[0]; int mark = Integer.parseInt(sheet.split(":")[1]); // old is null the first time; keep the larger mark topMark.compute(subject, (s, old) -> old == null || mark > old ? mark : old); } }, "hall-" + (h + 1)); threads.add(t); t.start(); } for (Thread t : threads) { t.join(); } System.out.println("Top marks: " + new TreeMap<>(topMark));
topMark.computeIfPresent("Physics", (s, old) -> old + 5); // grace marks, only if present topMark.computeIfPresent("Biology", (s, old) -> old + 5); // absent: nothing happens System.out.println("After grace: " + new TreeMap<>(topMark)); }}Top marks: {Chemistry=93, Maths=97, Physics=84}
After grace: {Chemistry=93, Maths=97, Physics=89}What this code does
- Three exam halls report marks at the same time.
computereads the current top mark and stores the larger one in a single step, so no hall can overwrite a higher mark with a lower one. computeIfPresentadds grace marks only to subjects in the map. ForBiology, which is absent, the function never runs and nothing is added.
Example 5 · computeIfPresent: sell until sold out
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;
public class ProductStockDemo { public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>(); stock.put("monitor", 100); stock.put("keyboard", 50);
List<Thread> counters = new ArrayList<>(); for (int c = 1; c <= 4; c++) { Thread t = new Thread(() -> { for (int i = 0; i < 30; i++) { // 4 x 30 = 120 orders for 100 monitors // sell one; returning null removes the entry when the last one is sold stock.computeIfPresent("monitor", (item, left) -> left > 1 ? left - 1 : null); } }, "checkout-" + c); counters.add(t); t.start(); } for (Thread t : counters) { t.join(); }
System.out.println("Monitor still listed: " + stock.containsKey("monitor")); System.out.println("Catalogue now: " + stock); }}Monitor still listed: false
Catalogue now: {keyboard=50}What this code does
- Four checkout counters take 120 orders for 100 monitors. Each call takes one away; when the last monitor is sold, the function returns
nulland the entry is removed. - The 20 orders after that find no
monitorkey, socomputeIfPresentdoes nothing. Stock never goes below zero, andkeyboardis untouched.
Use it for any read-modify-write that merge cannot express, such as "keep the highest mark" (Example 4).
computeIfPresent(key, (k, old) -> newValue) runs only when the key exists; for a missing key it does nothing and returns null. It is handy for updates that make sense only for existing entries, like stock that is removed when it reaches zero (Example 5).
putIfAbsent: add only if missing, value ready.computeIfAbsent: add only if missing, value built by a function.merge: combine a new value with the old one (counts, sums).compute/computeIfPresent: any other update based on the old value;nullremoves.
Why get-then-put is still a race
Integer old = map.get(k); map.put(k, old + 1); uses a thread-safe map, yet it loses updates. Each call is atomic on its own, but two threads can both get 41 and both put 42. One increment disappears. The same happens with containsKey followed by put.
Example 6 · get-then-put versus merge
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;
public class GetThenPutRaceDemo { public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<String, Integer> racy = new ConcurrentHashMap<>(); ConcurrentHashMap<String, Integer> safe = new ConcurrentHashMap<>();
List<Thread> servers = new ArrayList<>(); for (int s = 1; s <= 4; s++) { Thread t = new Thread(() -> { for (int i = 0; i < 100_000; i++) { Integer old = racy.get("tatkal"); // step 1: read racy.put("tatkal", old == null ? 1 : old + 1); // step 2: write (may overwrite)
safe.merge("tatkal", 1, Integer::sum); // one atomic step } }, "irctc-" + s); servers.add(t); t.start(); } for (Thread t : servers) { t.join(); }
System.out.println("Expected: 400000"); System.out.println("get then put: " + racy.get("tatkal")); System.out.println("merge: " + safe.get("tatkal")); }}Expected: 400000 get then put: 308469 merge: 400000
What this code does
- Both counters use a
ConcurrentHashMap. The get-then-put counter loses about a quarter of the bookings, and the number changes from run to run. mergereads, adds and writes in one atomic step, so it reaches exactly 400,000 on every run.
Example 6 runs both versions side by side with four threads. The get-then-put counter ends far below 400,000 and changes on every run; the merge counter is exact every time. The rule: if the new value depends on the old value, use one atomic method, never two separate calls. A thread-safe map does not make your logic thread-safe; atomic methods do.
Fix the error
Replace get-then-put with one atomic call
The total comes out too low. Pick the one line that fixes the race.
Round 1 of 2
Four threads count page views with a get and a put.
Error
Page views for /home: 7412 (expected 8000)
Next step
Check your understanding
12 quick questions