LOW-LEVEL DESIGN · CONCURRENCY FOR LLD · CONCURRENCY · 45 OF 48

Thread Safety in Java: Race Conditions, Locks and Atomics

Why shared mutable state breaks under threads and how to fix it in Java: race conditions, check-then-act and lost updates, synchronized, ReentrantLock, AtomicInteger and compare-and-set, ConcurrentHashMap atomic methods, visibility and volatile, deadlock and lock ordering, shown with two gates racing to book the last parking spot.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 163 lines, with a small main() demo. Save it as SpotBookingRace.java, then run javac SpotBookingRace.java && java SpotBookingRace.

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntConsumer;

/** Two gates race for one parking spot: the bug, then four ways to make it safe. */
public class SpotBookingRace {

    // ---------- 1. The problem: check-then-act with no protection ----------
    static final class UnsafeSpot {
        private String plate; // null means free

        boolean park(String p) {
            if (plate == null) {          // check
                pause();                  // widen the gap so the race shows up
                plate = p;                // act
                return true;
            }
            return false;
        }
    }

    // ---------- 2. Fix: synchronized makes check + act one step ----------
    static final class SyncSpot {
        private String plate;

        synchronized boolean park(String p) {
            if (plate == null) {
                pause();
                plate = p;
                return true;
            }
            return false;
        }
    }

    // ---------- 3. Fix: an explicit lock, always released in finally ----------
    static final class LockSpot {
        private final ReentrantLock lock = new ReentrantLock();
        private String plate;

        boolean park(String p) {
            lock.lock();
            try {
                if (plate == null) {
                    pause();
                    plate = p;
                    return true;
                }
                return false;
            } finally {
                lock.unlock();
            }
        }
    }

    // ---------- 4. Fix: compare-and-set, no lock at all ----------
    static final class CasSpot {
        private final AtomicReference<String> owner = new AtomicReference<>();

        boolean park(String p) {
            return owner.compareAndSet(null, p);
        }
    }

    // ---------- Visibility: a volatile flag is seen by other threads promptly ----------
    static volatile boolean lotOpen = true;

    public static void main(String[] args) throws InterruptedException {
        UnsafeSpot unsafe = new UnsafeSpot();
        SyncSpot sync = new SyncSpot();
        LockSpot locked = new LockSpot();
        CasSpot cas = new CasSpot();

        System.out.println("Unsafe spot, cars parked: " + countWins(8, i -> unsafe.park("CAR-" + i))
                + " (should be 1)");
        System.out.println("synchronized, cars parked: " + countWins(8, i -> sync.park("CAR-" + i)));
        System.out.println("ReentrantLock, cars parked: " + countWins(8, i -> locked.park("CAR-" + i)));
        System.out.println("compareAndSet, cars parked: " + countWins(8, i -> cas.park("CAR-" + i)));

        // Lost updates: plain int vs AtomicInteger, 4 threads x 20,000 entries each
        int[] plain = new int[1];
        AtomicInteger atomic = new AtomicInteger();
        race(4, i -> {
            for (int k = 0; k < 20_000; k++) {
                plain[0]++;               // read, add, write: not atomic
                atomic.incrementAndGet(); // one atomic step
            }
        });
        System.out.println("Plain counter: " + plain[0] + " (may be below 80000)");
        System.out.println("Atomic counter: " + atomic.get());

        // ConcurrentHashMap: atomic methods instead of get-then-put
        Map<String, String> ticketByPlate = new ConcurrentHashMap<>();
        Map<String, Integer> entriesPerGate = new ConcurrentHashMap<>();
        AtomicInteger issued = new AtomicInteger();
        race(6, i -> {
            String gate = i % 2 == 0 ? "A" : "B";
            entriesPerGate.merge(gate, 1, Integer::sum);
            if (ticketByPlate.putIfAbsent("KA-01-1234", "T-" + i) == null) {
                issued.incrementAndGet(); // only the first gate wins
            }
        });
        System.out.println("Tickets for the same plate: " + issued.get() + ", entries per gate: "
                + new java.util.TreeMap<>(entriesPerGate));

        // volatile flag: the board thread stops as soon as the lot closes
        Thread board = new Thread(() -> {
            while (lotOpen) {
                Thread.onSpinWait();
            }
            System.out.println("Board saw the lot close");
        });
        board.start();
        lotOpen = false;
        board.join();
    }

    /** Runs the task on many threads, released together, and counts how many returned true. */
    static int countWins(int threads, java.util.function.IntPredicate task) throws InterruptedException {
        AtomicInteger wins = new AtomicInteger();
        race(threads, i -> {
            if (task.test(i)) {
                wins.incrementAndGet();
            }
        });
        return wins.get();
    }

    /** Starts the threads, lets them all go at once with a latch, then waits for them. */
    static void race(int threads, IntConsumer task) throws InterruptedException {
        CountDownLatch start = new CountDownLatch(1);
        Thread[] all = new Thread[threads];
        for (int i = 0; i < threads; i++) {
            int id = i;
            all[i] = new Thread(() -> {
                try {
                    start.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
                task.accept(id);
            });
            all[i].start();
        }
        start.countDown();
        for (Thread t : all) {
            t.join();
        }
    }

    static void pause() {
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Notes

The race

Here is the race. Gate A asks if spot seven is free, and it is. Before Gate A writes its car in, Gate B asks the same question, and the spot is still free. Both gates park. Both drivers get a ticket for spot seven. Each thread did the right thing on its own. The bug lives in the gap between the check and the write, when another thread can sneak in.

Check-then-act

This shape is called check then act. You read a value, make a decision, then write, assuming the value has not changed in between. Without protection, that assumption is false. A race condition is any bug where the result depends on the timing of threads. These bugs are rare, so they slip through tests, and they get worse exactly when traffic is highest.

Check-then-act
boolean park(String plate) {
  if (this.plate == null) {  // check
    // another thread can run here
    this.plate = plate;      // act
    return true;
  }
  return false;
}

Lost updates

The second classic race is the lost update. Adding one to a counter looks like one step, but it is three: read the value, add one, write it back. If two threads both read forty one, both write forty two, and one increment vanishes. The occupancy counter drifts, and the board says a full lot has space. The same bug hits any balance plus equals amount style of code.

Read-modify-write
  • count++ is really:
  • 1 read count (say 41)
  • 2 add one (42)
  • 3 write 42
  • two threads both read 41,
  • both write 42:
  • one car entry is lost
  • same bug: balance += amount

synchronized

The simplest fix is the synchronized keyword. Every Java object has a built in lock called a monitor. A synchronized method takes the object's monitor before running and releases it after, even if an exception is thrown. Gate B now waits until Gate A has finished both the check and the write, then sees the spot is taken. The check and the act became one atomic step. Synchronized also makes Gate A's write visible to Gate B.

synchronized
synchronized boolean park(String p) {
  if (plate == null) {
    plate = p;
    return true;
  }
  return false;
}

ReentrantLock

ReentrantLock does the same job as an object with more control. You can try for the lock with a timeout and give up instead of waiting forever, you can wait in a way that responds to interruption, and you can ask for a fair lock that serves threads in order. The price is discipline: always unlock in a finally block. Forget it once and every other gate waits forever. Reentrant means the thread that holds it can lock it again without blocking itself.

ReentrantLock
private final Lock lock =
    new ReentrantLock();

lock.lock();
try {
  if (plate == null) { plate = p; ...}
} finally {
  lock.unlock();  // always
}

lock.tryLock(50, MILLISECONDS)

Compare-and-set

For a single value, atomics are often cleaner. Compare and set says: if the current value is still what I expect, replace it, all in one step done by the hardware. The spot keeps its owner in an AtomicReference. Gate A swaps empty for car A and wins. Gate B tries to swap empty for car B, but the value is no longer empty, so it fails and picks another spot. No lock, no waiting. AtomicInteger does the same for counters.

Lock-free booking
AtomicReference<String> owner =
    new AtomicReference<>();

boolean park(String plate) {
  return owner.compareAndSet(null, plate);
}

AtomicInteger free = ...;
free.decrementAndGet();

Retry loops

When a compare and set fails, you read the new value and try again. Methods like update and get run that retry loop for you. If many threads hammer one counter, LongAdder spreads the work across cells and is faster. But atomics protect one variable at a time. If two values must change together, like marking a spot taken and recording the ticket, use a lock around both.

Atomics: limits
  • CAS fails: read again, retry
  • updateAndGet(x -> x - 1)
  • does the loop for you
  • heavy contention on a
  • counter: LongAdder
  • two values that must change
  • together (spot + ticket):
  • use a lock

ConcurrentHashMap

Shared maps are next. A ConcurrentHashMap is safe for many threads at once, but only per call. Checking contains key and then calling put is check then act again, and two gates could both issue a ticket for the same plate. Use the atomic methods instead: put if absent, compute if absent, and merge for counting. Each one does the check and the write together.

Atomic map methods
// wrong: check-then-act again
if (!tickets.containsKey(plate))
  tickets.put(plate, ticket);

// right: one atomic call
tickets.putIfAbsent(plate, ticket);
entries.merge(gate, 1, Integer::sum);
tickets.computeIfAbsent(k, f);

Visibility

There is a quieter problem: visibility. Processors keep values in caches and registers, and the compiler may reorder or hoist reads. So when Gate B sets a lot closed flag, Gate A's loop might keep reading an old copy forever. The Java memory model only promises that a write is seen when there is a happens before link, created by locks, volatile fields, thread start and join, and the concurrent classes.

volatile

Marking a field volatile fixes visibility. Every write goes where other threads will see it, and every read gets the latest value. It is perfect for a simple flag like open or closed. But volatile does not make compound actions atomic. A volatile counter with plus plus is still three steps and still loses updates. Use volatile for flags and published references, and atomics or locks for anything that reads then writes.

volatile
private volatile boolean open = true;

// gate thread
while (open) { serveNextCar(); }

// admin thread
open = false;  // seen promptly

volatile int count;
count++;  // STILL a race

Deadlock

Locks bring their own danger: deadlock. Gate A holds the first lock and waits for the second, while Gate B holds the second and waits for the first. Neither ever moves. The standard fix is a global lock order: when you need two spots, always lock the lower spot id first. Other habits help too: use try lock with a timeout, keep locked sections short, and never call unknown code while holding a lock.

Avoid deadlock
  • A holds lock 1, wants lock 2
  • B holds lock 2, wants lock 1
  • nobody moves, ever
  • fixes:
  • • always lock in one order
  • (e.g. by spot id)
  • • tryLock with a timeout
  • • keep locked code short
  • • never call outside code
  • while holding a lock

Best fix: no sharing

Often the best fix is to avoid shared mutable state. Immutable objects, like Java records with final fields, can be shared by any number of threads with no locks at all. Confinement means only one thread ever touches some data. And when state must be shared and changed, keep it inside one small class and guard it there, so the thread safety story fits in one sentence during the interview.

Avoid the problem
  • immutable objects: records
  • with final fields, safe to
  • share freely
  • confinement: data owned by
  • one thread only
  • small shared core: keep
  • mutable state in one class
  • and guard it there

Pick the right tool

Here is a quick guide. A single flag: volatile. A counter: an atomic integer, or LongAdder under heavy load. Claiming one slot: compare and set. A shared map: ConcurrentHashMap with its atomic methods. Several values that must change together: synchronized or a lock. Need a timeout or fairness: ReentrantLock. Choosing the smallest tool that fits keeps code fast and easy to reason about.

Which tool?
  • one flag: volatile
  • one counter: AtomicInteger
  • or LongAdder
  • claim one slot: CAS
  • shared map: ConcurrentHashMap
  • + its atomic methods
  • several values together:
  • synchronized or a Lock
  • need timeout or fairness:
  • ReentrantLock

In LLD interviews

Every serious LLD problem asks this. Two gates and one spot, two users and one cinema seat, shared rate limiter counters, the last item in stock. Say which state is shared, describe the race, and name the exact fix. Common mistakes: making every method synchronized without thinking, locking on a new object each call so nothing is protected, and sharing a plain HashMap between threads.

Where it comes up
  • parking lot: two gates,
  • one spot
  • movie booking: two users,
  • one seat
  • rate limiter: shared counters
  • inventory: last item in stock
  • mistakes: synchronize every
  • method; lock on a new object;
  • HashMap shared across threads

Interview questions

What is a race condition?

A bug where the result depends on the timing of threads. Typical forms are check-then-act, where the checked value changes before the action, and read-modify-write, where two updates overwrite each other.

Why is count++ not thread safe?

It reads the value, adds one and writes it back as separate steps. Two threads can read the same old value and both write the same new value, so one increment is lost. Use AtomicInteger, LongAdder or a lock.

What is the difference between synchronized and ReentrantLock?

Both give mutual exclusion and visibility. synchronized is simpler and releases automatically. ReentrantLock adds tryLock with timeouts, interruptible waiting, optional fairness and multiple conditions, but you must unlock in a finally block.

How does compare-and-set work?

It atomically replaces a value only if it still equals the expected value, and reports whether it succeeded. If another thread changed it first, the call fails and you can re-read and retry, which allows lock-free updates of a single variable.

What does volatile guarantee?

Visibility and ordering: a write to a volatile field is seen by later reads in other threads, and it creates a happens-before link. It does not make compound actions like increment atomic.

Is ConcurrentHashMap enough to make my code thread safe?

Only for single calls. A get followed by a put is still a race. Use atomic methods such as putIfAbsent, computeIfAbsent, compute and merge so the check and the update happen together.

How do you prevent deadlock?

Acquire locks in one global order, keep locked sections small, avoid calling unknown code while holding a lock, and use tryLock with a timeout so a thread can back off instead of waiting forever.

How would you stop two gates from assigning the same parking spot?

Make claiming a spot atomic. Either keep the spot owner in an AtomicReference and use compareAndSet from empty to the plate, or guard the check and assignment with one lock. The losing gate simply tries the next spot.

Why are immutable objects thread safe?

Their state never changes after construction, so there is nothing for threads to race on. With final fields, Java guarantees other threads see the fully built object once they get a reference to it.