Locks and atomics: 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 bugs with locks and atomics come from a few habits: an unlock() that some path skips, two atomics that should change together, a check and an update done as two steps, and a tool chosen for speed instead of fit. Each has a short, reliable fix.
Mistake 1: unlock outside finally
An unlock() outside finally is skipped by any exception or early return between lock() and unlock(). The lock stays held, and the next thread that calls lock() hangs with no error message.
Example 1 · Mistake: unlock skipped by an exception
import java.util.concurrent.locks.ReentrantLock;
class ExamPortal { final ReentrantLock lock = new ReentrantLock(); private int submitted = 0;
void submitWrong(int answers) { lock.lock(); if (answers < 0) { throw new IllegalArgumentException("negative answers"); } submitted++; lock.unlock(); // skipped by the exception }
void submitRight(int answers) { lock.lock(); try { if (answers < 0) { throw new IllegalArgumentException("negative answers"); } submitted++; } finally { lock.unlock(); // runs on every path } }}
public class UnlockFinallyDemo { public static void main(String[] args) throws InterruptedException { ExamPortal wrong = new ExamPortal(); Thread t1 = new Thread(() -> { try { wrong.submitWrong(-1); } catch (IllegalArgumentException e) { System.out.println("wrong: " + e.getMessage()); } }, "student-1"); t1.start(); t1.join(); System.out.println("wrong: lock still held after student-1 finished? " + wrong.lock.isLocked());
ExamPortal right = new ExamPortal(); Thread t2 = new Thread(() -> { try { right.submitRight(-1); } catch (IllegalArgumentException e) { System.out.println("right: " + e.getMessage()); } }, "student-2"); t2.start(); t2.join(); System.out.println("right: lock still held after student-2 finished? " + right.lock.isLocked()); }}wrong: negative answers wrong: lock still held after student-1 finished? true right: negative answers right: lock still held after student-2 finished? false
What this code does
- Both methods throw for the same bad input. In
submitWrongthe exception jumps overunlock(), so the lock outlives the thread that took it. - Every later
submitWrongcall from any thread would now wait forever. Nothing is printed to warn you. submitRightuses the lock, try, finally pattern, so the lock is free again even though the exception still reaches the caller.
Two cousins of this bug: calling lock() inside the try (a failure there makes finally unlock a lock you never took), and ignoring the result of tryLock() (the code runs unprotected, and unlock() throws IllegalMonitorStateException). The fix is always the same shape: lock() just before try, the work inside try, unlock() in finally. With tryLock(), put that whole shape inside if (lock.tryLock()).
Mistake 2: two atomics updated separately
Two atomics are not one atomic. Each AtomicInteger call is safe on its own, but orders.incrementAndGet(); revenue.addAndGet(40); is two steps. A reader between them sees the new order count with the old revenue.
Example 2 · Mistake: orders and revenue in two atomics
import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.atomic.AtomicReference;
record Till(int orders, long revenue) { Till addOrder(long amount) { return new Till(orders + 1, revenue + amount); }}
public class TwoAtomicsDemo { static volatile boolean done;
public static void main(String[] args) throws InterruptedException { // Wrong: two separate atomics AtomicInteger orders = new AtomicInteger(); AtomicLong revenue = new AtomicLong(); long[] bad = new long[2]; done = false; Thread reader1 = new Thread(() -> { while (!done) { int o = orders.get(); long r = revenue.get(); if (r != o * 40L) { bad[0]++; } } }, "dashboard-1"); Thread writer1 = new Thread(() -> { for (int i = 0; i < 1_000_000; i++) { orders.incrementAndGet(); revenue.addAndGet(40); } done = true; }, "store-1"); reader1.start(); writer1.start(); writer1.join(); reader1.join();
// Right: one immutable record in one AtomicReference AtomicReference<Till> till = new AtomicReference<>(new Till(0, 0)); done = false; Thread reader2 = new Thread(() -> { while (!done) { Till t = till.get(); if (t.revenue() != t.orders() * 40L) { bad[1]++; } } }, "dashboard-2"); Thread writer2 = new Thread(() -> { for (int i = 0; i < 1_000_000; i++) { till.updateAndGet(t -> t.addOrder(40)); } done = true; }, "store-2"); reader2.start(); writer2.start(); writer2.join(); reader2.join();
System.out.println("Two atomics, mismatched reads: " + bad[0]); System.out.println("One record, mismatched reads: " + bad[1]); System.out.println("Final till: " + till.get()); }}Two atomics, mismatched reads: 2061943 One record, mismatched reads: 0 Final till: Till[orders=1000000, revenue=40000000]
What this code does
- A dashboard thread keeps reading while the store thread sells 1,000,000 orders of Rs 40. With two atomics it often catches orders and revenue out of step; the count changes on every run and can rarely be 0.
- With one
Tillrecord, the pair is replaced in a single atomic swap, so a reader can never see a half-updated pair: always 0 mismatches. - A lock around both updates and both reads would be just as correct.
Whenever two values must always agree (orders and revenue, min and max, seats and bookings), they need one guard. Either update and read both under one lock, or put both in one immutable record and swap it with AtomicReference.updateAndGet. The same applies to a check followed by an update on one atomic: if (n.get() < limit) n.incrementAndGet(); is two steps. Put the check inside getAndUpdate or a CAS loop.
Choosing lock, atomic or LongAdder
Pick the simplest tool that keeps your rule true. Ask what must be true about the data, then how it is used.
Example 3 · The right tool for each value in a booking app
import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.atomic.LongAdder;import java.util.concurrent.locks.ReentrantLock;
class BookingApp { final LongAdder searches = new LongAdder(); // busy counter, read rarely private final AtomicLong nextPnr = new AtomicLong(4_100_000_000L); // each booking needs its own number private final ReentrantLock seatLock = new ReentrantLock(); // seats and bookings must agree private int seatsLeft = 3; private int booked = 0;
String book(String name) throws InterruptedException { searches.increment(); if (!seatLock.tryLock(200, TimeUnit.MILLISECONDS)) { return name + ": busy, please try again"; } try { if (seatsLeft == 0) { return name + ": waitlisted"; } seatsLeft--; booked++; } finally { seatLock.unlock(); } return name + ": confirmed"; }
long newPnr() { return nextPnr.incrementAndGet(); }
String seats() { seatLock.lock(); try { return "Booked " + booked + ", left " + seatsLeft; } finally { seatLock.unlock(); } }}
public class RightToolDemo { public static void main(String[] args) throws InterruptedException { BookingApp app = new BookingApp(); for (int i = 0; i < 997; i++) { app.searches.increment(); } for (String name : new String[] {"Asha", "Bilal", "Charu", "Dev"}) { System.out.println(app.book(name)); } System.out.println("First PNR: " + app.newPnr()); System.out.println("Seats: " + app.seats()); System.out.println("Searches: " + app.searches.sum()); }}Asha: confirmed Bilal: confirmed Charu: confirmed Dev: waitlisted First PNR: 4100000001 Seats: Booked 3, left 0 Searches: 1001
What this code does
- Searches are a high-traffic count that is read only on reports, so
LongAdderfits. The PNR needs a unique number per caller, soAtomicLong.incrementAndGet()fits. seatsLeftandbookedmust always agree, so they share one lock.tryLockwith a timeout keeps the booking page from hanging.- Each choice follows from what must be true about the data, not from which tool is fastest.
- One number, many writers, read rarely (hits, likes, events):
LongAdder. - One number where each caller needs the result, or a limit (token IDs, seats left):
AtomicInteger/AtomicLongwithincrementAndGetorgetAndUpdate. - Several values that must change together, or long work on shared state: a lock (
synchronizedby default,ReentrantLockfor timeouts, fairness or conditions). - Data read far more often than written, with slow reads:
ReentrantReadWriteLock, or an immutable object behind anAtomicReference.
Mistake 3: check-then-act on an atomic
Check-then-act means reading a value, deciding something, then changing the value in a separate step. With atomics this looks safe because every call is atomic, but another thread can act between the check and the change.
// Wrong: two steps, two threads can both pass the check at 499if (count.get() < 500) { count.incrementAndGet();}
// Right: check and change in one atomic updateboolean accepted = count.getAndUpdate(n -> n < 500 ? n + 1 : n) < 500;The fix is to make the decision part of the atomic update: getAndUpdate(n -> n < limit ? n + 1 : n) returns the old value, and the old value tells you whether you got in. The same idea works with an explicit CAS loop.
Example 4 · Check-then-act on an atomic, acted out step by step
import java.util.concurrent.atomic.AtomicInteger;
public class CheckThenActDemo { static final int LIMIT = 500;
public static void main(String[] args) { // Two threads, played in a fixed order so the run is the same every time AtomicInteger wrong = new AtomicInteger(499); boolean aPasses = wrong.get() < LIMIT; // thread A checks: 499 < 500 boolean bPasses = wrong.get() < LIMIT; // thread B checks: 499 < 500 if (aPasses) wrong.incrementAndGet(); if (bPasses) wrong.incrementAndGet(); System.out.println("Check, then increment: " + wrong.get() + " registrations");
AtomicInteger right = new AtomicInteger(499); boolean aIn = right.getAndUpdate(n -> n < LIMIT ? n + 1 : n) < LIMIT; boolean bIn = right.getAndUpdate(n -> n < LIMIT ? n + 1 : n) < LIMIT; System.out.println("One getAndUpdate: " + right.get() + " registrations, A in? " + aIn + ", B in? " + bIn); }}Check, then increment: 501 registrations One getAndUpdate: 500 registrations, A in? true, B in? false
What this code does
- Both checks run before either increment, which is exactly what can happen with real threads. Both pass, so A registers 500 and B registers 501, and the limit is broken by one.
- With
getAndUpdate, the check is inside the atomic update. Whichever thread goes second sees 500 and changes nothing. - The returned old value tells each caller whether it got in, so no second
get()is needed.
Finish up
Mark complete & continue
Next: Why use a thread pool?