Why count++ is not safe
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)count++ looks like one step, but the computer does it as three: read the value, add 1, write the new value back. Another thread can run between those steps, and when it does, one of the two updates is lost.
count++ is read, add, write
An atomic operation happens completely or not at all, with no other thread seeing it half-done. count++ is not atomic: it reads, adds and writes in three steps.
count++ on a field is a read-modify-write: three separate steps that read the current value, add 1 to a private copy, and write the copy back. The code below writes those three steps out by hand.
int copy = count; // 1. read the shared valuecopy = copy + 1; // 2. add 1 to the private copycount = copy; // 3. write the copy backExample 1 · count++ written out as three steps
class Counter { int count = 5;}
public class ThreeStepsDemo { public static void main(String[] args) { Counter counter = new Counter();
int temp = counter.count; // step 1: read System.out.println("read: temp = " + temp); temp = temp + 1; // step 2: add (in a private copy) System.out.println("add: temp = " + temp); counter.count = temp; // step 3: write back System.out.println("write: count = " + counter.count);
counter.count++; System.out.println("after count++: " + counter.count); }}read: temp = 5 add: temp = 6 write: count = 6 after count++: 7
What this code does
- The three lines with
tempdo exactly whatcounter.count++does; the last line,counter.count++, does the same three steps in one line. Between step 1 and step 3 the new value exists only intemp, not in the shared field. - With one thread nothing can go wrong. With two threads, another thread can read the field while this thread's new value is still sitting in its private copy.
A thread can be paused, or another core can run, between any two of these steps. Each thread does the adding in its own private copy, much like a CPU register (a tiny storage slot inside the processor).
++count, count += 1 and count = count + 1 are the same three steps. Changing the spelling does not make it safe.
int n inside run() is still safe with n++: no other thread can reach it. The danger is only for shared fields, static fields and array elements.A step-by-step timeline of a lost update
A timeline lists the steps of every thread in the order they really happened. It is the best tool for understanding a race on paper.
Example 2 · Playing out a lost update on paper
class Counter { int count = 41;}
public class LostUpdateTimelineDemo { public static void main(String[] args) { Counter chart = new Counter(); int a; // thread A's private copy int b; // thread B's private copy
System.out.println("start: count = " + chart.count); a = chart.count; System.out.println("t1 A reads " + a); b = chart.count; System.out.println("t2 B reads " + b); a = a + 1; System.out.println("t3 A adds 1 " + a); b = b + 1; System.out.println("t4 B adds 1 " + b); chart.count = a; System.out.println("t5 A writes " + a); chart.count = b; System.out.println("t6 B writes " + b); System.out.println("end: count = " + chart.count + " (two increments, only +1)"); }}start: count = 41 t1 A reads 41 t2 B reads 41 t3 A adds 1 42 t4 B adds 1 42 t5 A writes 42 t6 B writes 42 end: count = 42 (two increments, only +1)
What this code does
- This is the railway chart from the previous lesson as code. B reads at t2, before A writes at t5, so B never sees A's change. At t6 B overwrites A's 42 with its own 42.
- One thread runs all the steps here, so the output never changes. Real threads produce this timeline only some of the time, which is why the real bug is hard to catch.
The program above plays out one bad timeline in a single thread, so it prints the same result every time. The variables a and b stand for the private copies of thread A and thread B. Both threads read 41 before either writes, so both write 42. This is a simplified model. Real CPUs also keep copies of memory in caches; the Visibility module covers that part.
Trace the code
Trace one bad timeline of two increments
Step through one timeline in which two threads each add 1 to count (41).
Variables
- count
- 41
- a
- 41
Output
(nothing printed yet)Line 5Thread A reads the shared count (41) into its private copy a.
Why the final count changes from run to run
Interleaving is the way the steps of different threads mix in time. The thread scheduler decides which thread runs when, and it never plans exactly the same way twice.
Example 3 · All six orders of two increments
public class AllOrdersDemo { // Plays one order. "Ar" = A reads, "Aw" = A writes its copy + 1 (same for B). static int play(String order) { int count = 0; int a = 0; int b = 0; for (String step : order.split(" ")) { switch (step) { case "Ar" -> a = count; case "Aw" -> count = a + 1; case "Br" -> b = count; case "Bw" -> count = b + 1; default -> throw new IllegalArgumentException(step); } } return count; }
public static void main(String[] args) { String[] orders = { "Ar Aw Br Bw", "Br Bw Ar Aw", "Ar Br Aw Bw", "Ar Br Bw Aw", "Br Ar Aw Bw", "Br Ar Bw Aw" }; int safe = 0; for (String order : orders) { int result = play(order); String verdict = result == 2 ? "correct" : "lost update"; System.out.println(order + " -> count = " + result + " (" + verdict + ")"); if (result == 2) { safe++; } } System.out.println("Safe orders: " + safe + " of " + orders.length); }}Ar Aw Br Bw -> count = 2 (correct) Br Bw Ar Aw -> count = 2 (correct) Ar Br Aw Bw -> count = 1 (lost update) Ar Br Bw Aw -> count = 1 (lost update) Br Ar Aw Bw -> count = 1 (lost update) Br Ar Bw Aw -> count = 1 (lost update) Safe orders: 2 of 6
What this code does
- Each thread always reads before it writes, but the scheduler can mix the two threads in six ways. The add happens in a private copy, so only the positions of the reads and writes matter.
- Only the two orders where one thread finishes before the other starts are correct. Whenever both reads happen before both writes, one update is lost.
Example 4 · Counting lost UPI payment records
class PaymentLog { int recorded = 0;
void record() { recorded++; }}
public class LostPaymentsDemo { public static void main(String[] args) throws InterruptedException { PaymentLog log = new PaymentLog(); Runnable server = () -> { for (int i = 0; i < 1_000_000; i++) { log.record(); } }; Thread s1 = new Thread(server, "upi-server-1"); Thread s2 = new Thread(server, "upi-server-2"); s1.start(); s2.start(); s1.join(); s2.join();
int expected = 2_000_000; int lost = expected - log.recorded; System.out.println("Payments made: " + expected); System.out.println("Payments recorded: " + log.recorded); System.out.println("Payments lost: " + lost); }}Payments made: 2000000 Payments recorded: 1452318 Payments lost: 547682
What this code does
- Every lost record is one of the bad orders from Example 3 happening in real time. How many happen depends on how often the two threads overlap, so the numbers change on every run.
- On some runs, especially on a busy computer, very few or no records are lost. The code is just as wrong on those runs.
For two threads doing one count++ each, there are only six possible orders of their read and write steps. Two orders are safe and four lose an update. In a loop of a million increments, the threads overlap at random moments, so the number of lost updates is different on every run. The number of CPU cores, other programs on the computer and the JIT compiler (the part of the JVM that turns busy code into fast machine code) all change the timing. That is why the same program can lose many updates on one machine and few on another.
Why a test that passes once proves nothing
A flaky test is a test that passes on some runs and fails on others without any change to the code. Tests of code with a race condition are often flaky.
Example 5 · A small test passes, a big test fails
class Counter { int count = 0;
void increment() { count++; }}
public class FlakyTestDemo { static void testCounter(int perThread) throws InterruptedException { Counter counter = new Counter(); Runnable task = () -> { for (int i = 0; i < perThread; i++) { counter.increment(); } }; Thread a = new Thread(task, "test-1"); Thread b = new Thread(task, "test-2"); a.start(); b.start(); a.join(); b.join();
int expected = 2 * perThread; String result = counter.count == expected ? "PASS" : "FAIL"; System.out.println(perThread + " per thread: " + result + " (" + counter.count + " of " + expected + ")"); }
public static void main(String[] args) throws InterruptedException { testCounter(1_000); testCounter(1_000_000); }}1000 per thread: PASS (2000 of 2000) 1000000 per thread: FAIL (1517902 of 2000000)
What this code does
- The
Counterclass is the same in both tests. With 1,000 increments the first thread usually finishes before the second gets going, so nothing overlaps and the test passes. - With a million increments the threads run at the same time and updates are lost. On your computer either line may differ, which is exactly what makes such tests flaky.
- Use many iterations and run the test many times.
- Run it on a machine with several cores.
- Still trust the code review over the test: no shared read-modify-write without taking turns.
A small test is the worst case. With only a thousand increments per thread, the first thread often finishes before the second one even starts, so the threads never overlap and the test passes. The bug is still there: it waits for more load, more cores or worse timing. So a passing run is not proof of safety. Read the code instead: if two threads can do a read-modify-write on the same data without taking turns, it is a race, however many runs pass.
Next step
Check your understanding
11 quick questions