Collections.synchronizedList and its limits
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Collections.synchronizedList and Collections.synchronizedMap turn an ordinary ArrayList or HashMap into a thread-safe one in a single line. They fix the lost items from the last lesson, but they protect only one method call at a time, and that leaves three traps every Java developer must know.
synchronizedList and synchronizedMap
Collections.synchronizedList(list) returns a wrapper: a new List object that holds your list inside it and runs every method, such as add, get and size, inside a synchronized block. synchronizedMap, synchronizedSet and synchronizedCollection work the same way.
Example 1 · Wrapping a list and a map
import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;
public class WrapperBasicsDemo { public static void main(String[] args) throws InterruptedException { List<Integer> tickets = Collections.synchronizedList(new ArrayList<>()); Map<Integer, String> results = Collections.synchronizedMap(new HashMap<>());
Runnable work = () -> { String me = Thread.currentThread().getName(); for (int i = 0; i < 100_000; i++) { tickets.add(i); // locked by the wrapper results.put(me.equals("counter-1") ? i : 100_000 + i, "PASS"); } };
Thread t1 = new Thread(work, "counter-1"); Thread t2 = new Thread(work, "counter-2"); t1.start(); t2.start(); t1.join(); t2.join();
System.out.println("List size: " + tickets.size()); System.out.println("Map size: " + results.size()); }}List size: 200000 Map size: 200000
What this code does
- The same two-thread test that lost items with a plain
ArrayListnow always ends with 200,000 items, because everyaddandputruns under the wrapper's lock. - The wrapped
HashMapalso keeps all 200,000 entries. Nothing else in the code changed: only the line that creates each collection.
All methods of one wrapper use one lock, and that lock is the wrapper object itself. So two threads can never be inside add and get of the same wrapper at the same time, and no item is lost. After wrapping, use only the wrapper. If some code still holds the original ArrayList and calls add on it directly, that call takes no lock and the old race is back.
List<Integer> list = Collections.synchronizedList(new ArrayList<>());, so no variable ever points at the unwrapped list.Compound actions are still not atomic
A compound action is two or more calls that must happen together, such as "check if the seat is free, then book it". The wrapper locks each call, but it releases the lock between them. Another thread can run in that gap.
Example 2 · Tatkal double booking with a synchronized map
import java.util.Collections;import java.util.HashMap;import java.util.Map;
class Agent implements Runnable { private final Map<Integer, String> seats; int confirmed = 0; // seats this agent thinks it booked
Agent(Map<Integer, String> seats) { this.seats = seats; }
@Override public void run() { String me = Thread.currentThread().getName(); for (int seat = 1; seat <= 100_000; seat++) { if (!seats.containsKey(seat)) { // check ... seats.put(seat, me); // ... then act: two separate calls confirmed++; } } }}
public class DoubleBookingDemo { public static void main(String[] args) throws InterruptedException { Map<Integer, String> seats = Collections.synchronizedMap(new HashMap<>()); Agent a = new Agent(seats); Agent b = new Agent(seats); Thread t1 = new Thread(a, "agent-A"); Thread t2 = new Thread(b, "agent-B"); t1.start(); t2.start(); t1.join(); t2.join();
int tickets = a.confirmed + b.confirmed; System.out.println("Seats in the train: " + seats.size()); System.out.println("Tickets confirmed: " + tickets); System.out.println("Double-booked: " + (tickets - seats.size())); }}Seats in the train: 100000 Tickets confirmed: 112555 Double-booked: 12555
What this code does
containsKeyandputare each locked, but the lock is released between them. Both agents often see a seat as free and both confirm it, so more tickets are confirmed than seats exist.- The map itself is not damaged (it has exactly 100,000 seats). The bug is in the logic around it, and the count changes from run to run.
Example 3 · Fixing it with client-side locking
import java.util.Collections;import java.util.HashMap;import java.util.Map;
class Agent implements Runnable { private final Map<Integer, String> seats; int confirmed = 0;
Agent(Map<Integer, String> seats) { this.seats = seats; }
@Override public void run() { String me = Thread.currentThread().getName(); for (int seat = 1; seat <= 100_000; seat++) { synchronized (seats) { // the same lock the wrapper uses if (!seats.containsKey(seat)) { seats.put(seat, me); confirmed++; } } } }}
public class LockedBookingDemo { public static void main(String[] args) throws InterruptedException { Map<Integer, String> seats = Collections.synchronizedMap(new HashMap<>()); Agent a = new Agent(seats); Agent b = new Agent(seats); Thread t1 = new Thread(a, "agent-A"); Thread t2 = new Thread(b, "agent-B"); t1.start(); t2.start(); t1.join(); t2.join();
int tickets = a.confirmed + b.confirmed; System.out.println("Seats in the train: " + seats.size()); System.out.println("Tickets confirmed: " + tickets); System.out.println("Double-booked: " + (tickets - seats.size())); }}Seats in the train: 100000 Tickets confirmed: 100000 Double-booked: 0
What this code does
synchronized (seats)holds the wrapper's own lock across both calls, so check and book happen as one step. Exactly 100,000 tickets are confirmed on every run.- Locking
seatsmatters: it is the same lock the wrapper's own methods use, so no other wrapper call can slip in between.
In Example 2, two booking agents both call containsKey(seat), both see false, and both call put. Two passengers get a ticket for one seat. The fix in Example 3 is client-side locking: the calling code wraps both calls in synchronized (seats). It must lock the wrapper object itself, because that is the lock every wrapper method uses. Java 8 added putIfAbsent, merge and compute to Map. The synchronized wrapper runs each of them under its lock, so each one is a single atomic step. if (seats.putIfAbsent(seat, me) == null) books a seat safely with no extra block.
this or a private lock, does not stop wrapper calls made elsewhere: they still use only the wrapper's lock.Iteration must be locked by hand
A for-each loop calls iterator() once and then hasNext() and next() many times. The wrapper locks iterator() but not the loop that follows, so another thread can add items while you are halfway through.
Example 4 · Looping without the lock
import java.util.ArrayList;import java.util.Collections;import java.util.ConcurrentModificationException;import java.util.List;
public class UnlockedLoopDemo { static volatile boolean writerDone = false;
public static void main(String[] args) throws InterruptedException { List<Integer> fees = Collections.synchronizedList(new ArrayList<>()); for (int i = 0; i < 1_000; i++) { fees.add(500); }
Thread reader = new Thread(() -> { try { while (!writerDone) { long total = 0; for (int f : fees) { // the loop itself is NOT locked total += f; } } System.out.println("reader: no error this time"); } catch (ConcurrentModificationException e) { System.out.println("reader: stopped by ConcurrentModificationException"); } }, "fee-report");
Thread writer = new Thread(() -> { for (int i = 0; i < 100_000; i++) { fees.add(750); // each add() is locked } writerDone = true; }, "fee-writer");
reader.start(); writer.start(); reader.join(); writer.join(); System.out.println("final size: " + fees.size()); }}reader: stopped by ConcurrentModificationException final size: 101000
What this code does
- Every
fees.addis locked, but the reader's for-each loop is not. The writer adds items in the middle of the loop and the iterator throws on most runs. - The final size is always 101,000 because the adds themselves are safe. Only the loop is broken.
Example 5 · Locking the loop, or looping over a snapshot
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class LockedLoopDemo { public static void main(String[] args) throws InterruptedException { List<Integer> fees = Collections.synchronizedList(new ArrayList<>()); for (int i = 0; i < 1_000; i++) { fees.add(500); }
Thread reader = new Thread(() -> { for (int pass = 0; pass < 200; pass++) { long total = 0; synchronized (fees) { // hold the wrapper's lock for the whole loop for (int f : fees) { total += f; } } } System.out.println("reader: 200 passes, no error"); }, "fee-report");
Thread writer = new Thread(() -> { for (int i = 0; i < 100_000; i++) { fees.add(750); // waits while the reader holds the lock } }, "fee-writer");
reader.start(); writer.start(); reader.join(); writer.join(); System.out.println("final size: " + fees.size());
List<Integer> snapshot = new ArrayList<>(fees); // one locked copy, then loop freely System.out.println("snapshot size: " + snapshot.size()); }}reader: 200 passes, no error final size: 101000 snapshot size: 101000
What this code does
synchronized (fees)around the loop holds the wrapper's lock for the whole pass. The writer'saddwaits for each pass to finish, so the reader never sees a half-changed list.new ArrayList<>(fees)copies the list in one call that the wrapper locks for you. The copy belongs tomainalone, so looping over it needs no lock.
The Java documentation says you must hold the wrapper's lock yourself while you iterate.
Example 4 loops without the lock and gets a ConcurrentModificationException. Example 5 puts the whole loop inside synchronized (fees), so the writer simply waits until the loop is finished.
The same rule covers stream() and spliterator(). A few whole-collection calls are already locked by the wrapper: forEach, removeIf, toString and toArray. That is why new ArrayList<>(fees) makes a safe snapshot (a copy at one moment): you can then loop over the copy with no lock at all.
One lock for everything slows threads down
Contention means many threads want the same lock at the same time, so all but one must wait. A synchronized wrapper has one lock for every method, so it suffers from contention.
Contention means many threads want the same lock at the same time, so all but one wait in a line. A synchronized wrapper has exactly one lock for every method, so every thread competes for it.
Example 6 · A long report blocks a quick lookup
import java.util.Collections;import java.util.HashMap;import java.util.Map;
public class OneLockWaitDemo { static volatile boolean reportStarted = false;
public static void main(String[] args) throws InterruptedException { Map<String, Integer> balances = Collections.synchronizedMap(new HashMap<>()); balances.put("asha@upi", 1200); balances.put("ravi@upi", 300);
Thread report = new Thread(() -> { synchronized (balances) { // a long report holds the one lock reportStarted = true; for (String id : balances.keySet()) { sleepMillis(100); } } }, "night-report"); report.start(); while (!reportStarted) { sleepMillis(5); // wait until the report has the lock }
long start = System.nanoTime(); int balance = balances.get("ravi@upi"); // a tiny read, but it needs the same lock 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: true
What this code does
- The night report holds the map's lock for about 200 ms. Meanwhile
mainwants one balance, butgetneeds the same lock, so it waits for the report to finish. - With many threads this waiting adds up: all readers and writers form one line behind a single lock, however many CPU cores the server has.
Readers block other readers, even though two get calls could safely run together. A long loop under the lock, like the night report in Example 6, makes a tiny get wait for the whole report. Adding CPU cores does not help, because only one thread can hold the lock. For a few threads and light use, a wrapper is simple and fine. For a busy shared map, such as a result server with dozens of threads, ConcurrentHashMap lets many threads read and write at once. It is the topic of the next lesson.
- Good fit: few threads, small collection, occasional updates.
- Poor fit: many threads, frequent reads, long loops over the data.
Next step
Check your understanding
12 quick questions