Lost updates and broken invariants
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Making every field thread-safe does not make a class thread-safe. When a rule connects two or more fields, the whole rule must be protected, or other threads will see data that is half updated.
Two fields that must change together
An invariant is a rule about your data that must always be true, such as booked berths plus free berths equal the total. Code that changes the data must keep the rule true for every other thread.
An invariant is a rule about your data that must always be true, for example "booked berths + free berths = 72" in a sleeper coach.
Example 1 · Two atomic counters, one broken rule
import java.util.concurrent.atomic.AtomicInteger;
class SleeperCoach { // rule (invariant): booked + free == 72 at all times final AtomicInteger booked = new AtomicInteger(0); final AtomicInteger free = new AtomicInteger(72);
void book() { booked.incrementAndGet(); // each line is atomic on its own... free.decrementAndGet(); // ...but the pair is not }
void cancel() { booked.decrementAndGet(); free.incrementAndGet(); }}
public class CoachCountersDemo { static boolean anyAlive(Thread[] threads) { for (Thread t : threads) { if (t.isAlive()) return true; } return false; }
public static void main(String[] args) throws InterruptedException { SleeperCoach coach = new SleeperCoach(); Thread[] agents = new Thread[4]; for (int i = 0; i < agents.length; i++) { agents[i] = new Thread(() -> { for (int j = 0; j < 100_000; j++) { coach.book(); coach.cancel(); } }, "agent-" + (i + 1)); agents[i].start(); }
int checks = 0, wrong = 0; while (anyAlive(agents)) { int sum = coach.booked.get() + coach.free.get(); checks++; if (sum != 72) wrong++; } for (Thread t : agents) t.join();
System.out.println("Checks while booking: " + checks + ", wrong sums seen: " + wrong); System.out.println("At the end: booked " + coach.booked.get() + ", free " + coach.free.get()); }}Checks while booking: 4275315, wrong sums seen: 538718 At the end: booked 0, free 72
What this code does
bookchanges two counters. Each call is atomic, butmaincan read between them, or readbookedbefore one agent's update andfreeafter it, and get a sum other than 72.- The final numbers are right (0 booked, 72 free), so a test that checks only the end would pass. The wrong sums appear only while the agents work, and the count changes on every run.
When a rule links two fields, both must change in one step that no other thread can see half done.
Making each field safe on its own is not enough. With two AtomicIntegers, booked.incrementAndGet() and free.decrementAndGet() are each atomic, but between the two calls another thread can read a sum of 73. This is a broken invariant: no single update is lost, yet other threads see data that breaks the rule.
A min-max range that becomes invalid
A check-then-act across two fields breaks the same way. A marks range keeps lower and upper with the rule lower ≤ upper. setLower(5) checks 5 ≤ upper (10): fine. setUpper(4) checks 4 ≥ lower (0): fine.
Example 2 · Both checks pass, the range breaks
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.atomic.AtomicInteger;
class MarksRange { // rule: lower <= upper private final AtomicInteger lower = new AtomicInteger(0); private final AtomicInteger upper = new AtomicInteger(10);
static final CyclicBarrier bothChecked = new CyclicBarrier(2);
void setLower(int value) throws InterruptedException, BrokenBarrierException { if (value > upper.get()) { // check... throw new IllegalArgumentException("lower > upper"); } bothChecked.await(); lower.set(value); // ...then act }
void setUpper(int value) throws InterruptedException, BrokenBarrierException { if (value < lower.get()) { throw new IllegalArgumentException("upper < lower"); } bothChecked.await(); upper.set(value); }
String show() { int lo = lower.get(), hi = upper.get(); return "[" + lo + ", " + hi + "]" + (lo <= hi ? " valid" : " INVALID"); }}
public class BrokenRangeDemo { public static void main(String[] args) throws InterruptedException { MarksRange range = new MarksRange(); System.out.println("Start: " + range.show());
Thread a = new Thread(() -> { try { range.setLower(5); } catch (Exception e) { System.out.println("setLower failed: " + e.getMessage()); } }, "set-lower"); Thread b = new Thread(() -> { try { range.setUpper(4); } catch (Exception e) { System.out.println("setUpper failed: " + e.getMessage()); } }, "set-upper"); a.start(); b.start(); a.join(); b.join();
System.out.println("End: " + range.show()); }}Start: [0, 10] valid End: [5, 4] INVALID
What this code does
- The
CyclicBarriermakes both threads finish their checks before either one writes, so the bad timing happens on every run. Without it, the same bug appears only now and then. - Each setter used
AtomicInteger, yet the range ended as [5, 4]. Atomic fields do not make a rule across fields atomic.
Run both at once, and each check passes against the old value of the other field. Both writes happen and the range ends as [5, 4].
Each thread made a correct check. The bug is that the check and the write are two separate steps, and the other field can change in between. This is also how a lost update happens: one thread's change is overwritten or ignored because another thread acted on old data.
Total money changing during transfers
In a bank, the rule is that the total of all balances never changes during a transfer. If withdraw and deposit are separately synchronized, each is safe, but between the two calls the money is in neither account.
Example 3 · The audit sees money missing
class Account { private int balance;
Account(int balance) { this.balance = balance; }
synchronized void withdraw(int amount) { balance -= amount; } synchronized void deposit(int amount) { balance += amount; } synchronized int balance() { return balance; }}
public class BankAuditDemo { // each step is thread-safe, but the transfer as a whole is not one step static void transfer(Account from, Account to, int amount) { from.withdraw(amount); // here the money is in neither account to.deposit(amount); }
static Thread repeat(Account from, Account to) { Thread t = new Thread(() -> { for (int i = 0; i < 200_000; i++) transfer(from, to, 10); }); t.start(); return t; }
public static void main(String[] args) throws InterruptedException { Account a = new Account(10_000), b = new Account(10_000), c = new Account(10_000); Thread[] movers = { repeat(a, b), repeat(b, c), repeat(c, a) };
int audits = 0, wrong = 0; while (movers[0].isAlive() || movers[1].isAlive() || movers[2].isAlive()) { int total = a.balance() + b.balance() + c.balance(); audits++; if (total != 30_000) wrong++; } for (Thread t : movers) t.join();
System.out.println("Audits during transfers: " + audits + ", wrong totals: " + wrong); System.out.println("Total after all transfers: " + (a.balance() + b.balance() + c.balance())); }}Audits during transfers: 75931, wrong totals: 39365 Total after all transfers: 30000
What this code does
- Every method of
Accountissynchronizedand the final total is correct, yet tens of thousands of audits saw a wrong total. Your numbers will differ on each run. - Two problems add up: a transfer is two separate locked steps, and the audit reads the three accounts one at a time. Both must happen under one lock to give a true total.
An auditor who adds up the balances at that moment sees money missing.
The final total is still correct, so a test that checks only the end result passes. The bug hurts readers in between: an audit report, a balance screen, or a rule such as "freeze the bank if the total drops".
Guarding a whole invariant with one lock
The fix is to protect the whole rule, not each field. Every field in the rule is guarded by the same lock, and every method that reads or writes any of them, including the check, takes that lock.
Example 4 · One lock for both ends of the range
class MarksRange { // rule: lower <= upper. Both fields are guarded by the same lock: 'this'. private int lower = 0; private int upper = 10;
synchronized void setLower(int value) { if (value > upper) throw new IllegalArgumentException("lower > upper"); lower = value; // check and act in one locked step }
synchronized void setUpper(int value) { if (value < lower) throw new IllegalArgumentException("upper < lower"); upper = value; }
synchronized boolean isValid() { return lower <= upper; }
synchronized String show() { return "[" + lower + ", " + upper + "]"; }}
public class SafeRangeDemo { public static void main(String[] args) throws InterruptedException { MarksRange range = new MarksRange();
Thread lowerSetter = new Thread(() -> { for (int i = 0; i < 100_000; i++) { try { range.setLower(5); } catch (IllegalArgumentException e) { /* rejected */ } range.setLower(0); } }); Thread upperSetter = new Thread(() -> { for (int i = 0; i < 100_000; i++) { try { range.setUpper(4); } catch (IllegalArgumentException e) { /* rejected */ } range.setUpper(10); } }); lowerSetter.start(); upperSetter.start();
int invalid = 0; while (lowerSetter.isAlive() || upperSetter.isAlive()) { if (!range.isValid()) invalid++; } lowerSetter.join(); upperSetter.join();
System.out.println("Invalid ranges seen: " + invalid); System.out.println("End: " + range.show()); }}Invalid ranges seen: 0 End: [0, 10]
What this code does
setLowerandsetUppercheck and write inside the same lock (this), andisValidreads under it too. The checker never saw an invalid range while 200,000 updates raced.- When the setters race now, one wins and the other sees the new value and throws. A rejected update is a correct result; an invalid range is not.
Example 5 · One immutable object instead of two counters
import java.util.concurrent.atomic.AtomicReference;
// both numbers live in one immutable object, so they always change togetherrecord CoachState(int booked, int free) {}
class SleeperCoach { private final AtomicReference<CoachState> state = new AtomicReference<>(new CoachState(0, 72));
void book() { state.updateAndGet(s -> new CoachState(s.booked() + 1, s.free() - 1)); }
void cancel() { state.updateAndGet(s -> new CoachState(s.booked() - 1, s.free() + 1)); }
CoachState snapshot() { return state.get(); } // one read gives a matching pair}
public class CoachSnapshotDemo { public static void main(String[] args) throws InterruptedException { SleeperCoach coach = new SleeperCoach(); Thread[] agents = new Thread[4]; for (int i = 0; i < agents.length; i++) { agents[i] = new Thread(() -> { for (int j = 0; j < 100_000; j++) { coach.book(); coach.cancel(); } }, "agent-" + (i + 1)); agents[i].start(); }
int wrong = 0; boolean running = true; while (running) { CoachState s = coach.snapshot(); if (s.booked() + s.free() != 72) wrong++; running = false; for (Thread t : agents) running |= t.isAlive(); } for (Thread t : agents) t.join();
System.out.println("Wrong sums seen: " + wrong); System.out.println("At the end: " + coach.snapshot()); }}Wrong sums seen: 0 At the end: CoachState[booked=0, free=72]
What this code does
CoachStateholds both numbers.updateAndGetbuilds a new record from the current one and swaps it in atomically, retrying if another thread changed it first.- The reader calls
snapshot()once and gets both numbers from the same moment, so the sum is always 72. No lock is needed on the read side.
Example 6 · One bank lock for transfers and audits
class Bank { // rule: the total of all balances never changes. One lock guards the whole rule. private final Object lock = new Object(); private final int[] balances = {10_000, 10_000, 10_000};
void transfer(int from, int to, int amount) { synchronized (lock) { balances[from] -= amount; balances[to] += amount; } }
int total() { synchronized (lock) { // the audit takes the same lock return balances[0] + balances[1] + balances[2]; } }}
public class BankOneLockAuditDemo { static Thread repeat(Bank bank, int from, int to) { Thread t = new Thread(() -> { for (int i = 0; i < 200_000; i++) bank.transfer(from, to, 10); }); t.start(); return t; }
public static void main(String[] args) throws InterruptedException { Bank bank = new Bank(); Thread[] movers = { repeat(bank, 0, 1), repeat(bank, 1, 2), repeat(bank, 2, 0) };
int wrong = 0; while (movers[0].isAlive() || movers[1].isAlive() || movers[2].isAlive()) { if (bank.total() != 30_000) wrong++; } for (Thread t : movers) t.join();
System.out.println("Wrong totals seen during transfers: " + wrong); System.out.println("Total after all transfers: " + bank.total()); }}Wrong totals seen during transfers: 0 Total after all transfers: 30000
What this code does
transferandtotalboth take the bank's singlelock, so an audit never runs in the middle of a transfer. Zero wrong totals, on every run.- This is the one-lock idea from the deadlock lessons, used here for correctness: one lock is the simplest way to guard a rule that spans many accounts.
No thread can then see the data between two steps. When the fields are few and small, a second clean fix is one immutable object: put the values in a record such as CoachState(booked, free) and keep it in an AtomicReference or a volatile field. An update builds a new record and swaps it in one step, so one read always returns a matching pair.
- Use the same lock for every field in the rule, and for the readers too.
- Keep the check and the act inside the same locked block.
- Or keep the fields in one immutable object and replace it in one atomic step.
Next step
Check your understanding
11 quick questions