Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Computer Basics / Operating Systems

    Race Conditions and Locks

    A bug where the result depends on the exact timing of threads is a race condition.

    Chapter 8 of 126 min read

    The Plain Picture#

    You and your sister share a whiteboard showing "Chocolates left: 10". You both eat one at the same moment. Each of you:

    1. reads the board: "10",

    2. works out 10 − 1 = 9,

    3. writes "9".

    Two chocolates were eaten but the board says 9. One update was lost, because you both read before either of you wrote.

    The fix: a rule that only the person holding the marker may read-and-update the board. You take the marker, read, update, and put the marker down; only then can your sister take it.

    The Real Names#

    • A bug where the result depends on the exact timing of threads is a race condition.

    • The bit of code that touches shared data and must not be interrupted by another thread doing the same is a critical section.

    • The marker is a lock, also called a mutex (mutual exclusion). Only one thread can hold it at a time; others wait.

    • An operation that happens as one indivisible step — no thread can ever see it half-done — is atomic.

    Under the Hood#

    Why count++ is not one step#

    count++ looks like one operation. The CPU actually does three (How Computers Work Ch 5):

    Output
      1. LOAD   count from memory into a register
      2. ADD    1 to the register
      3. STORE  the register back to memory

    Two threads, interleaved by the scheduler (Ch 4):

      time   Thread A                 Thread B                count in memory
      ────   ───────────────────      ───────────────────     ───────────────
       1     LOAD  (reads 10)                                        10
       2                              LOAD  (reads 10)               10
       3     ADD   → 11                                              10
       4                              ADD   → 11                     10
       5     STORE 11                                                11
       6                              STORE 11                       11   ← should be 12!

    See it happen (real output)#

    This Java program has two threads each add 1 a million times, once unsafely and once with an atomic counter:

    Java
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class Race {
        static int count = 0;
        static AtomicInteger safeCount = new AtomicInteger(0);
    
        public static void main(String[] args) throws InterruptedException {
            Runnable work = () -> {
                for (int i = 0; i < 1_000_000; i++) {
                    count++; // race condition
                    safeCount.incrementAndGet(); // atomic
                }
            };
            Thread a = new Thread(work);
            Thread b = new Thread(work);
            a.start();
            b.start();
            a.join();
            b.join();
            System.out.println("unsafe: " + count);
            System.out.println("safe:   " + safeCount.get());
        }
    }

    Three real runs on a Mac with 8 cores:

    Output
      unsafe: 1300437    safe: 2000000
      unsafe: 1109071    safe: 2000000
      unsafe: 1079772    safe: 2000000

    The unsafe count is different every time and always wrong. That randomness is the signature of a race condition — and why they're so hard to find: the bug may not show up in testing at all.

    Three ways to fix it#

    1. A lock around the critical section:

      Java
      synchronized (lockObject) {
          // only one thread at a time can be inside
          count++;
      }
    2. An atomic operation — the CPU has special instructions (like compare-and-swap) that do read-modify-write as one indivisible step. AtomicInteger uses them. Faster than a lock for simple counters.

    3. Don't share. Give each thread its own counter and add them up at the end. Often the best answer.

    The same bug, outside one program#

    Race conditions aren't only about threads. Two web requests can race too:

    Output
      Request A: read StudyBuddy credits from the database → 1
      Request B: read credits → 1
      Request A: 1 ≥ 1, allow the AI question, write credits = 0
      Request B: 1 ≥ 1, allow the AI question, write credits = 0   ← two questions for one credit

    The fixes are the same ideas at database level — row locks, atomic updates like UPDATE ... SET credits = credits - 1 WHERE credits > 0 — taught in Transactions and Isolation (coming soon).

    Gotchas

    • Locks slow things down if held too long or too often — threads spend their time waiting. Keep critical sections short.

    • "It worked in testing" proves nothing about race conditions. They depend on timing, and production load changes the timing.

    • Reading shared data needs care too. Without proper synchronization, one thread may not even see another thread's writes promptly (because of CPU caches and compiler reordering). Use the language's thread-safe tools rather than clever tricks.

    Check yourself

    4 questions
    1

    Why is count++ not safe with two threads?

    Show answer

    It's three steps (load, add, store); two threads can interleave them and lose updates.

    2

    What is a critical section?

    Show answer

    Code that touches shared data and must only be run by one thread at a time.

    3

    Give three ways to fix a shared counter.

    Show answer

    A lock (mutex/synchronized), an atomic operation (AtomicInteger), or giving each thread its own counter and combining at the end.

    4

    Describe a race condition between two web requests.

    Show answer

    Two requests read the same balance before either writes, so both think they can spend it — e.g. one credit used twice.