Chapter 10 · Simulation

Thread Race

← Chapter 10
Java code
Shared memoryvalue
0
Interleaving order (last 4)
    1000 runs

    no runs yet

    Thread Race

    Goal: see why some increments can be lost (a race condition) when two threads increment the value field of the same object, and how synchronized and AtomicInteger prevent it.

    Why are they lost?

    value++ is not a single operation: the value is read from memory (r = value), incremented in the thread's own copy (r = r + 1) and written back to memory (value = r). If two threads read the same old value and both write, the second write overwrites the increment of the first: a lost update. Threads cannot choose the order in which they run; the scheduler decides it.

    The fixes

    • synchronized: a thread entering the method acquires the object's lock (monitor). While the lock is held, the other thread waits in the BLOCKED state; read-increment-write completes without being split.
    • AtomicInteger: incrementAndGet() works without locks. Here a compareAndSet loop is shown conceptually: if the value that was read is still in memory, the new value is written; if not, it is read again. On most processors the JVM does this with a single atomic machine instruction.

    How to use it

    1. With T1 ▶ and T2 ▶ you choose which thread runs one step (keys 1 and 2 on the keyboard). Random runs one random step, Finish finishes with a random order.
    2. 1000 runs does 1000 random orderings with the selected counter and draws the distribution of the final values (green bar: the expected 2k).
    3. Task: create a lost update on the unprotected counter, or reach the smallest result that is possible. With two threads that each increment k times, the possible results are 1–2 for k = 1 and 2–2k for k ≥ 2 (found by trying all orderings).

    In a real Java 8 run, two threads that each incremented 100,000 times gave results between 194,246 and 199,180 on the unprotected counter in five attempts; in the same loop the synchronized and AtomicInteger counters gave 200,000 every time.

    Related slides: Chapter 10 · Threads (Race Condition, Why Does counter++ Get Lost?, synchronized and the Monitor, Preventing the Race).