Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 12 / Topic 2 of 7

Race conditions, and synchronized

A race condition is a bug where the correct result depends on the exact timing of two or more threads — and "correct" only shows up by luck. unsafeBalance = unsafeBalance + amount looks like one step; it is actually three separate operations (read, add, write), and the JVM gives no guarantee that one thread's read-add-write happens before another thread starts its own. Think of two people reading the same whiteboard number, both doing "+1" in their head, and both writing their own answer back — whichever one writes second erases the other's update, and the board ends up one short.

synchronized on a method (or a block) says: only one thread may execute this code, on this lock, at a time. Every other thread that reaches a synchronized block on the same lock simply waits.

static int unsafeBalance = 0;
static void depositUnsafe(int amount) {
    unsafeBalance = unsafeBalance + amount;   // read, add, write: three separate steps
}

static int safeBalance = 0;
static synchronized void depositSafe(int amount) {
    safeBalance = safeBalance + amount;       // only one thread runs this method body at a time
}
$ javac RaceAndSynchronized.java
$ java RaceAndSynchronized
== without synchronized: a lost-update race ==
expected: 1000000
actual (unsafe): 326429  (varies -- a different wrong number on every run)
lost updates happened: true

== with synchronized: every deposit counted ==
expected: 1000000
actual (safe): 1000000
correct every time: true

Four threads each deposit 1 rupee a million times total; the unsafe version lost roughly two-thirds of those deposits to overlapping read-add-write sequences — a different wrong number on every single run, which is exactly what makes race conditions dangerous: the bug doesn't announce itself. synchronized on depositSafe makes the whole read-add-write atomic from every other thread's point of view, and the total comes out exactly right, every time.

⚠️ "It worked when I tested it" proves nothing about a race condition. A race can pass a thousand runs in a row and then fail in production under different timing. Reason about whether shared mutable state is protected; don't rely on observed behavior.

Visibility: synchronized is about more than atomicity

A second, subtler hazard: even a single boolean flag read by one thread and written by another isn't guaranteed to be seen promptly — or ever — without some form of synchronization. The JVM and the CPU are both allowed to keep a thread's own cached copy of a variable instead of re-reading memory every time, as a normal, legal optimization.

static boolean plainStop = false;
static volatile boolean volatileStop = false;   // volatile: every read/write goes through main memory, visible to all threads
$ javac VisibilityCheck.java
$ java VisibilityCheck
== plain boolean flag (no 'volatile') ==
plain worker stopped within 500 ms: false  (JVM/hardware dependent -- may be true or false on your machine)

== volatile boolean flag ==
volatile worker saw the flag after 155867408 spins (varies)
volatile worker stopped within 500 ms: true

On this run, the worker spinning on the plain boolean never saw main set it to true within the 500 ms window — it's still spinning when the program gives up waiting on it (a daemon thread, so the JVM exits anyway). The volatile version saw the update and stopped cleanly. volatile doesn't make an operation atomic (two threads can still race on a volatile int++) — it only guarantees that a write by one thread becomes visible to a read by another. synchronized gives you both atomicity and visibility for the code inside the block, which is why it's the default tool reached for first.

Full program: examples/VisibilityCheck.java.

Deadlock: the hazard two locks introduce

A deadlock happens when two threads each hold a lock the other one needs, and neither can let go until it gets the other — both wait forever. It only takes two synchronized blocks, locked in opposite order by two different threads. Think of two people trying to pass each other in a narrow doorway, each one politely waiting for the other to step back first — neither will ever move again.

// Thread 1 calls transfer(a, b, ...): locks a, then b
// Thread 2 calls transfer(b, a, ...): locks b, then a
synchronized (from) {
    Thread.sleep(pauseMillisBetweenLocks);   // widens the window where the other thread can jump in
    synchronized (to) { ... }
}
$ javac DeadlockDemo.java
$ java DeadlockDemo
== two transfers, opposite lock order: a deadlock ==
transfer-A-to-B state: BLOCKED
transfer-B-to-A state: BLOCKED
deadlocked (both BLOCKED, neither can finish): true

== the fix: always lock accounts in the same order ==
both transfers finished (no deadlock)
X balance: 5200, Y balance: 4800
total unchanged: true

transfer-A-to-B grabs account A's lock, then waits to grab B's; transfer-B-to-A grabs B's lock first, then waits for A's — each is BLOCKED waiting on a lock the other one is holding, permanently. Thread.getState() reporting BLOCKED for both, at the same time, is the concrete proof. The fix needs no new API: always acquire locks in the same, fixed order regardless of which account is "from" and which is "to" (here, by comparing account IDs) — then two transfers in opposite logical directions still take their locks in the same physical order, and the second thread always finishes before the first one needs anything new.

🔍 Going deeper: jcmd <pid> Thread.print (Part 13) dumps every thread's state and stack, including a deadlock detection section — the exact tool you'd reach for if this happened in a real, long-running service instead of a small demo.

Full program: examples/DeadlockDemo.java.

Done here? The practice set for Part 12 — including the solutions — is on the part page.

Search the guide