Race conditions: 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 race conditions come from a few habits: reading shared data without the lock, locking a different object than the other threads, and checking and acting in two separate steps. Each has a short fix, and every fix can be explained in one sentence: which data is shared and which lock guards it.
Mistake 1: unsynchronized reads
Writers take the lock, but a getter or a report method reads the fields with no lock. It can read in the middle of an update and show numbers that never existed together, and Java does not even promise it sees the latest values.
Example 1 · Mistake: a report that reads without the lock
class ResultBoard { private final Object lock = new Object(); private int passed = 0; // guarded by lock: passed + failed == checked private int failed = 0; private int checked = 0;
void record(boolean pass) { synchronized (lock) { if (pass) { passed++; } else { failed++; } checked++; } }
boolean consistentNoLock() { // wrong: no lock return passed + failed == checked; }
boolean consistentLocked() { // right: same lock as record() synchronized (lock) { return passed + failed == checked; } }}
public class UnlockedReportDemo { public static void main(String[] args) throws InterruptedException { ResultBoard board = new ResultBoard(); Thread e1 = new Thread(() -> { for (int i = 0; i < 2_000_000; i++) board.record(i % 3 != 0); }, "evaluator-1"); Thread e2 = new Thread(() -> { for (int i = 0; i < 2_000_000; i++) board.record(i % 4 != 0); }, "evaluator-2"); int[] wrong = new int[2]; Thread unlocked = new Thread(() -> { while (e1.isAlive() || e2.isAlive()) { if (!board.consistentNoLock()) wrong[0]++; } }, "report-unlocked"); Thread locked = new Thread(() -> { while (e1.isAlive() || e2.isAlive()) { if (!board.consistentLocked()) wrong[1]++; } }, "report-locked"); e1.start(); e2.start(); unlocked.start(); locked.start(); e1.join(); e2.join(); unlocked.join(); locked.join(); System.out.println("Wrong: unlocked report saw broken totals " + wrong[0] + " times"); System.out.println("Fixed: locked report saw broken totals " + wrong[1] + " times"); }}Wrong: unlocked report saw broken totals 692 times Fixed: locked report saw broken totals 0 times
What this code does
- Every write is locked, yet the unlocked report sometimes lands between
passed++andchecked++and sees totals that do not add up. That count changes from run to run, and on a busy computer it can even be 0 on some runs. - The locked report uses the same
lockasrecord(), so it only ever sees complete updates and the second count is 0 on every run.
The fix is to read under the same lock as the writers. When the caller needs several related values, return them together from one locked method, as a record or a ready-made string, rather than from separate getters.
Mistake 2: locking on the wrong object
A lock protects data only against threads that lock the same object.
Example 2 · Mistake: two methods, two different locks
class MixedLockStock { private final Object lock = new Object(); private int units = 0;
synchronized void add() { // locks this units++; }
void remove() { synchronized (lock) { // locks a different object units--; } }
synchronized int units() { return units; }}
class OneLockStock { private final Object lock = new Object(); private int units = 0; // guarded by lock
void add() { synchronized (lock) { units++; } }
void remove() { synchronized (lock) { units--; } }
int units() { synchronized (lock) { return units; } }}
public class WrongObjectDemo { public static void main(String[] args) throws InterruptedException { MixedLockStock mixed = new MixedLockStock(); OneLockStock one = new OneLockStock(); Thread supplier = new Thread(() -> { for (int i = 0; i < 1_000_000; i++) { mixed.add(); one.add(); } }, "supplier"); Thread buyer = new Thread(() -> { for (int i = 0; i < 1_000_000; i++) { mixed.remove(); one.remove(); } }, "buyer"); supplier.start(); buyer.start(); supplier.join(); buyer.join(); System.out.println("Wrong: two locks -> " + mixed.units() + " (should be 0)"); System.out.println("Fixed: one lock -> " + one.units()); }}Wrong: two locks -> -1249 (should be 0) Fixed: one lock -> 0
What this code does
- In
MixedLockStock,addlocks the object andremovelockslock, so a supplier and a buyer never wait for each other and their updates collide. The first number changes from run to run. - In
OneLockStockevery method uses the same privatelock, so the second number is 0 on every run. The rule to check: one shared field, one lock.
The usual slips are: one method uses synchronized (which locks this) while another uses synchronized (lock); each worker object has its own lock field; synchronized (new Object()); and locks on Integer or String literals.
The fix is one lock per piece of shared data, kept as a private final field inside the class that owns the data, and used by every method that touches it. When reviewing, write down for each shared field the one lock that guards it; if you find two, that is the bug.
Mistake 3: check-then-act in booking code
The check and the act run under the lock, but not under the same hold of the lock: isFree(seat) then reserve(seat), a check block followed by an act block, containsKey then put, or if (instance == null) without a lock.
Example 3 · Mistake: isFree and reserve as two calls
import java.util.HashMap;import java.util.Map;
class Cinema { private final Map<String, String> seats = new HashMap<>();
synchronized boolean isFree(String seat) { return !seats.containsKey(seat); }
synchronized void reserve(String seat, String name) { seats.put(seat, name); }
synchronized boolean tryReserve(String seat, String name) { if (seats.containsKey(seat)) { return false; } seats.put(seat, name); return true; }}
public class SeatBookingDemo { static int soldTwoCalls = 0; static int soldOneCall = 0;
public static void main(String[] args) throws InterruptedException { Cinema hall1 = new Cinema(); Cinema hall2 = new Cinema(); Object countLock = new Object(); Runnable customer = () -> { String me = Thread.currentThread().getName(); if (hall1.isFree("A5")) { // check... pause(50); hall1.reserve("A5", me); // ...then act: two calls synchronized (countLock) { soldTwoCalls++; } } if (hall2.tryReserve("A5", me)) { // one atomic call synchronized (countLock) { soldOneCall++; } } }; Thread meera = new Thread(customer, "Meera"); Thread kabir = new Thread(customer, "Kabir"); meera.start(); kabir.start(); meera.join(); kabir.join(); System.out.println("Wrong: bookings for seat A5 = " + soldTwoCalls); System.out.println("Fixed: bookings for seat A5 = " + soldOneCall); }
static void pause(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}Wrong: bookings for seat A5 = 2 Fixed: bookings for seat A5 = 1
What this code does
isFreeandreserveare each synchronized, but the lock is released between them. Both customers see A5 free while choosing snacks, both reserve it, and the secondputsilently replaces the first.tryReservechecks and puts under one hold of the lock, so exactly one customer gets A5 on every run. The first line depends on timing; the 50 ms pause makes it happen on almost every run.
In between, another thread can make the check false.
The fix is one method that checks and acts inside one locked block and reports the result, such as boolean tryReserve(seat, name). Callers then cannot split the action even by accident. Slow steps like payment go outside, using reserve, pay, then confirm or release.
How to fix a race, step by step
A fix-the-race review is a short routine you can apply to any class used by many threads. It works for the exercises below and for real code.
- List the shared mutable data: fields, static fields and collections that more than one thread can reach and that change.
- Find every compound action on it: read-modify-write, check-then-act, and updates of fields linked by one invariant.
- Choose a fix: do not share (each thread owns its data), one owner thread, or one private lock around each whole compound action.
- Make every read of that data use the same lock, and never return internal mutable objects.
- Move slow work out of the lock, then test with many threads and many runs, while trusting the review more than the test.
Example 4 · Applying the review to a food-order desk
import java.util.ArrayList;import java.util.List;
final class OrderDesk { private final Object lock = new Object(); private int placed = 0; // guarded by lock: private int delivered = 0; // placed == delivered + pending.size() private final List<String> pending = new ArrayList<>();
void place(String order) { synchronized (lock) { placed++; pending.add(order); } }
String deliverNext() { String order; synchronized (lock) { if (pending.isEmpty()) { return null; } order = pending.remove(0); delivered++; } return order; // caller handles slow work outside }
String summary() { synchronized (lock) { return "placed " + placed + ", delivered " + delivered + ", pending " + pending.size(); } }}
public class OrderDeskDemo { public static void main(String[] args) throws InterruptedException { OrderDesk desk = new OrderDesk(); Thread app1 = new Thread(() -> { for (int i = 0; i < 5000; i++) desk.place("A" + i); }, "app-1"); Thread app2 = new Thread(() -> { for (int i = 0; i < 5000; i++) desk.place("B" + i); }, "app-2"); app1.start(); app2.start(); app1.join(); app2.join();
Runnable rider = () -> { for (int i = 0; i < 4000; i++) desk.deliverNext(); }; Thread r1 = new Thread(rider, "rider-1"); Thread r2 = new Thread(rider, "rider-2"); r1.start(); r2.start(); r1.join(); r2.join(); System.out.println(desk.summary()); }}placed 10000, delivered 8000, pending 2000
What this code does
- Shared data:
placed,deliveredandpending, linked by one invariant, so one private lock guards all three. Compound actions: placing (count and add) and delivering (check empty, remove, count), each in one block. summary()reads all three under the lock in one call, anddeliverNext()returns the order so any slow work happens outside. The output is the same on every run.
Finish up
Mark complete & continue
Next: When a thread cannot see a change