Concurrent collections: common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most concurrent-collection bugs come from a few habits: looping over a synchronized wrapper without its lock, splitting one update into two calls, trusting the map to protect the objects stored in it, and picking a collection that does not match how the data is used. Each has a short, reliable fix.
Mistake 1: looping over a synchronized wrapper without its lock
A synchronized wrapper locks each method call, but a for-each loop is many calls (hasNext, next, …) on an iterator. If another thread changes the collection during the loop, you get a ConcurrentModificationException or silently wrong data.
Example 1 · Mistake: an unlocked loop over a synchronized list
import java.util.ArrayList;import java.util.Collections;import java.util.ConcurrentModificationException;import java.util.List;
public class WrapperLoopMistakeDemo { static volatile boolean writerDone;
static String sumWhileWriting(List<Integer> fees, boolean lockTheLoop) throws InterruptedException { writerDone = false; String[] result = {"no error"}; Thread report = new Thread(() -> { try { while (!writerDone) { long total = 0; if (lockTheLoop) { synchronized (fees) { // the fix: hold the wrapper's lock for (int f : fees) total += f; } } else { for (int f : fees) total += f; // the mistake: loop not locked } } } catch (ConcurrentModificationException e) { result[0] = "ConcurrentModificationException"; } }, "fee-report"); Thread counter = new Thread(() -> { for (int i = 0; i < 50_000; i++) { fees.add(1_500); } writerDone = true; }, "fee-counter"); report.start(); counter.start(); counter.join(); report.join(); return result[0]; }
public static void main(String[] args) throws InterruptedException { List<Integer> a = Collections.synchronizedList(new ArrayList<>(List.of(500, 700))); System.out.println("Loop without the lock: " + sumWhileWriting(a, false));
List<Integer> b = Collections.synchronizedList(new ArrayList<>(List.of(500, 700))); System.out.println("Loop inside synchronized (fees): " + sumWhileWriting(b, true)); }}Loop without the lock: ConcurrentModificationException Loop inside synchronized (fees): no error
What this code does
- Both runs share a synchronized list with a writer adding 50,000 fees. The unlocked loop usually crashes with a CME; on another run it might instead read a wrong total without any error.
- With
synchronized (fees)around the loop, the writer'saddwaits until each pass ends, so the loop always finishes cleanly.
The fix is to hold synchronized (wrapper) around the whole loop, or to loop over a copy.
Be careful with copies too. new ArrayList<>(syncList) is safe, because it copies through toArray(), which the wrapper locks. But new HashMap<>(syncMap) and new TreeMap<>(syncMap) copy by looping over entrySet(), which is not locked, so they need synchronized (syncMap) around them as well.
ConcurrentHashMap or a CopyOnWriteArrayList instead of a wrapper.Mistake 2: get-then-put and check-then-act races
A thread-safe collection makes each single call safe, not your sequence of calls. get followed by put loses updates, and containsKey followed by put lets two threads both "win" the same key.
Example 2 · Mistake: two calls where one atomic call is needed
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
public class CompoundRaceMistakeDemo { public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<String, Integer> viewsWrong = new ConcurrentHashMap<>(); ConcurrentHashMap<String, Integer> viewsRight = new ConcurrentHashMap<>(); ConcurrentHashMap<Integer, String> seatsWrong = new ConcurrentHashMap<>(); ConcurrentHashMap<Integer, String> seatsRight = new ConcurrentHashMap<>(); AtomicInteger winsWrong = new AtomicInteger(); AtomicInteger winsRight = new AtomicInteger();
List<Thread> threads = new ArrayList<>(); for (int t = 1; t <= 4; t++) { String me = "counter-" + t; Thread th = new Thread(() -> { for (int i = 0; i < 50_000; i++) { // Mistake: get then put Integer old = viewsWrong.get("home"); viewsWrong.put("home", old == null ? 1 : old + 1); viewsRight.merge("home", 1, Integer::sum); } for (int seat = 1; seat <= 20_000; seat++) { // Mistake: check then act if (!seatsWrong.containsKey(seat)) { seatsWrong.put(seat, me); winsWrong.incrementAndGet(); } if (seatsRight.putIfAbsent(seat, me) == null) { winsRight.incrementAndGet(); } } }, me); threads.add(th); th.start(); } for (Thread th : threads) { th.join(); }
System.out.println("Page views, get then put: " + viewsWrong.get("home") + " (expected 200000)"); System.out.println("Page views, merge: " + viewsRight.get("home")); System.out.println("Seats won, containsKey then put: " + winsWrong.get() + " (20000 seats)"); System.out.println("Seats won, putIfAbsent: " + winsRight.get()); }}Page views, get then put: 145837 (expected 200000) Page views, merge: 200000 Seats won, containsKey then put: 23718 (20000 seats) Seats won, putIfAbsent: 20000
What this code does
- Get-then-put loses tens of thousands of page views, and containsKey-then-put "wins" more seats than exist. Both numbers change from run to run, on a
ConcurrentHashMap. mergeandputIfAbsentdo the read and the write as one step, so their numbers are exact every time.
These bugs pass small tests and appear only under real load, like an IRCTC rush at 10 a.m.
The fix is one atomic method: merge for counts and totals, putIfAbsent for first-come claims, computeIfAbsent for caches and groups, and compute or computeIfPresent for any other change based on the old value. On a synchronized wrapper you can also lock the wrapper around both calls.
Choosing the right collection
Pick the collection by how the data is used, not by habit. The questions are: how many threads, how often each one reads and writes, and whether threads need to wait for each other.
Example 3 · The right collection for each job
import java.util.ArrayList;import java.util.List;import java.util.TreeMap;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CopyOnWriteArrayList;import java.util.function.Consumer;
public class CampusAppDemo { // Shared counts, updated by many threads -> ConcurrentHashMap + merge static final ConcurrentHashMap<String, Integer> visits = new ConcurrentHashMap<>(); // Read on every event, changed rarely -> CopyOnWriteArrayList static final List<Consumer<String>> listeners = new CopyOnWriteArrayList<>(); // Work handed from producers to a consumer, memory-safe -> bounded BlockingQueue static final BlockingQueue<String> printJobs = new ArrayBlockingQueue<>(10);
public static void main(String[] args) throws InterruptedException { List<String> notified = new CopyOnWriteArrayList<>(); listeners.add(msg -> notified.add("app: " + msg)); listeners.add(msg -> notified.add("email: " + msg));
List<Thread> students = new ArrayList<>(); for (int s = 1; s <= 3; s++) { int id = s; Thread t = new Thread(() -> { for (int i = 0; i < 1_000; i++) { visits.merge(i % 2 == 0 ? "/timetable" : "/results", 1, Integer::sum); } try { printJobs.put("hall-ticket-" + id); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "student-" + s); students.add(t); t.start(); }
Thread printer = new Thread(() -> { try { for (int i = 0; i < 3; i++) { printJobs.take(); } for (Consumer<String> l : listeners) { l.accept("3 hall tickets printed"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "printer"); printer.start();
for (Thread t : students) { t.join(); } printer.join();
System.out.println("Visits: " + new TreeMap<>(visits)); System.out.println("Notifications: " + notified); }}Visits: {/results=1500, /timetable=1500}
Notifications: [app: 3 hall tickets printed, email: 3 hall tickets printed]What this code does
- Page visits are counted by three threads in a
ConcurrentHashMapwithmerge. Hall-ticket print jobs go through a boundedArrayBlockingQueueto one printer thread, which waits withtake. - The notification listeners sit in a
CopyOnWriteArrayList, because they are read on every event and almost never change.
- Shared map with real traffic →
ConcurrentHashMapwith atomic methods (merge,compute,putIfAbsent). - Small list read on every event, changed rarely (listeners, settings) →
CopyOnWriteArrayList. - Work handed from producers to consumers who should wait → bounded
ArrayBlockingQueueorLinkedBlockingQueue. - Few threads, light use, or wrapping a special collection such as a
TreeMap→Collections.synchronizedXxx, with locked loops.
ArrayList or HashMap and merge the results after join().Mistake 3: values the map does not protect
A ConcurrentHashMap protects its own entries, not the objects stored inside them. map.computeIfAbsent(key, k -> new ArrayList<>()).add(x) is a classic trap: the map call is atomic, but add then runs on a plain ArrayList shared by every thread.
Example 4 · Mistake: an ArrayList inside a ConcurrentHashMap
import java.util.ArrayList;import java.util.List;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;
public class UnprotectedValueMistakeDemo { public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<String, List<Integer>> wrongGroups = new ConcurrentHashMap<>(); ConcurrentHashMap<String, Set<Integer>> rightGroups = new ConcurrentHashMap<>();
List<Thread> threads = new ArrayList<>(); for (int t = 0; t < 4; t++) { int first = t * 25_000; Thread th = new Thread(() -> { for (int id = first; id < first + 25_000; id++) { String branch = id % 2 == 0 ? "CSE" : "ECE"; try { // Mistake: the map is safe, the ArrayList inside it is not wrongGroups.computeIfAbsent(branch, b -> new ArrayList<>()).add(id); } catch (RuntimeException e) { // a broken ArrayList can even throw; ignore it so the demo keeps going } // Fix: a thread-safe inner set rightGroups.computeIfAbsent(branch, b -> ConcurrentHashMap.newKeySet()).add(id); } }, "admission-desk-" + (t + 1)); threads.add(th); th.start(); } for (Thread th : threads) { th.join(); }
int wrongTotal = wrongGroups.get("CSE").size() + wrongGroups.get("ECE").size(); int rightTotal = rightGroups.get("CSE").size() + rightGroups.get("ECE").size(); System.out.println("Students grouped, ArrayList values: " + wrongTotal + " (expected 100000)"); System.out.println("Students grouped, newKeySet values: " + rightTotal); }}Students grouped, ArrayList values: 98839 (expected 100000) Students grouped, newKeySet values: 100000
What this code does
- Four admission desks group 100,000 students by branch. With
ArrayListvalues, students go missing (and anaddcan even throw), because every desk adds to the same unprotected list. The number changes from run to run. - With
ConcurrentHashMap.newKeySet()as the value, both the map and the inner sets are thread-safe, and all 100,000 students are kept.
The same goes for int[] counters, StringBuilder values or any mutable object.
Use a thread-safe value (ConcurrentHashMap.newKeySet(), AtomicInteger, LongAdder, a synchronized list), or keep values immutable and replace them with merge or compute. The same thinking applies to size(): it is a separate, approximate reading, so never enforce a limit with if (map.size() < LIMIT) map.put(...).
Finish up
Mark complete & continue
Next: CountDownLatch: wait for N tasks