SyntaxPilot
Courses/Java/Lesson 40
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 40 of 51

Synchronization, deadlock, volatile

queued

These are the notes for Java episode 40. Ravi and Asha both sell at the counter and drop every sale into one cash box. Two threads, one shared field, and money goes missing: a race condition. We see why (total = total + amount is three steps: read, add, write), and invent the fix: one key for the box, synchronized, then smaller synchronized blocks and AtomicInteger. Locks bring a new danger, deadlock, fixed by taking locks in one fixed order. Finally a cook never notices the shutter coming down, a visibility problem fixed by volatile. Every example was run with javac 21.

Threaded programs can give different output on every run. The outputs below are real runs; with a race condition your wrong number will be different, and with several threads printing, the line order may differ.

The problem: money goes missing

class CashBox {
    private int total = 0;
    void add(int amount) {
        int now = total;               // 1. read the box
        Thread.yield();                // 2. count the notes...
        total = now + amount;          // 3. write the new total
    }
    int total() { return total; }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CashBox box = new CashBox();
        Runnable cook = () -> { for (int i = 0; i < 100_000; i++) box.add(1); };
        Thread ravi = new Thread(cook), asha = new Thread(cook);
        ravi.start(); asha.start(); ravi.join(); asha.join();
        System.out.println("In box: Rs " + box.total() + " of Rs 200000");
    }
}

Output:

In box: Rs 107651 of Rs 200000

Two cooks each add Rs 1 a hundred thousand times, so the box should hold Rs 2,00,000 (two lakh). It holds far less, and a different amount every run. No exception, no error: just a wrong answer. A race condition is a bug where the result depends on the timing of threads.

About Thread.yield(): it lets the other thread run at that moment. It doesn't create the bug, it only widens a window that always exists between the read and the write, so the demo loses money on every run. Without it, the same code still loses updates, just less often, which makes the bug even harder to find.

Why: read, add, write

Step Ravi Asha Slip shows
1 reads 100 100
2 reads 100 100
3 writes 100 + 15 = 115 115
4 writes 100 + 12 = 112 112: Ravi's Rs 15 is lost

total = total + amount and total++ look like one step but are three: read the field, add, write it back. When two threads interleave those steps, one write overwrites the other: a lost update. The code that touches shared data and must not be interleaved is called a critical section.

synchronized: one key for the cash box

Real-life example: one key for the cash box.

At the counter In Java Meaning
One key on a hook lock (monitor) every Java object has one built-in lock
Take key, read-add-write, return key synchronized take the lock, run the code, release the lock
The other cook waits for the key BLOCKED state a thread waiting to take a lock (episode 39)
class CashBox {
    private int total = 0;
    synchronized void add(int amount) {
        int now = total;               // 1. read the box
        Thread.yield();                // 2. count the notes...
        total = now + amount;          // 3. write the new total
    }
    synchronized int total() { return total; }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CashBox box = new CashBox();
        Runnable cook = () -> { for (int i = 0; i < 100_000; i++) box.add(1); };
        Thread ravi = new Thread(cook), asha = new Thread(cook);
        ravi.start(); asha.start(); ravi.join(); asha.join();
        System.out.println("In box: Rs " + box.total() + " of Rs 200000");
    }
}

Output:

In box: Rs 200000 of Rs 200000
  • A synchronized instance method locks this (the object it's called on: here, the box).
  • A static synchronized method locks the class object (Main.class).
  • Only one thread at a time can hold a given lock; others wait in the BLOCKED state.
  • The lock is released when the method ends, even by an exception.
  • synchronized also gives visibility: what one thread wrote before releasing the lock is seen by the next thread that takes it. That's why total() is synchronized too.

synchronized blocks: lock only what's shared

A lock makes other threads wait, so hold it as briefly as possible. A synchronized (lockObject) { ... } block locks just the lines that touch shared data. Using a private lock object means no code outside the class can grab your lock by accident.

class Stall {
    private final Object cashLock = new Object();
    private int cash = 0;
    void sell(int price) {
        int bill = price + 5;                    // own work: no lock needed
        synchronized (cashLock) { cash += bill; }   // only the shared part
    }
    int cash() { synchronized (cashLock) { return cash; } }
}
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Stall s = new Stall();
        Runnable ravi = () -> { for (int i = 0; i < 50_000; i++) s.sell(15); };
        Runnable asha = () -> { for (int i = 0; i < 50_000; i++) s.sell(10); };
        Thread a = new Thread(ravi), b = new Thread(asha);
        a.start(); b.start(); a.join(); b.join();
        System.out.println("In box: Rs " + s.cash() + " of Rs 1750000");
    }
}

Output:

In box: Rs 1750000 of Rs 1750000

AtomicInteger: one unbreakable step

java.util.concurrent.atomic.AtomicInteger does read-add-write as one atomic step (it can't be split or interleaved), without synchronized.

import java.util.concurrent.atomic.AtomicInteger;

class CashBox {
    private final AtomicInteger total = new AtomicInteger(0);
    void add(int amount) {
        total.addAndGet(amount);       // read + add + write, as ONE step
    }
    int total() { return total.get(); }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CashBox box = new CashBox();
        Runnable cook = () -> { for (int i = 0; i < 100_000; i++) box.add(1); };
        Thread ravi = new Thread(cook), asha = new Thread(cook);
        ravi.start(); asha.start(); ravi.join(); asha.join();
        System.out.println("In box: Rs " + box.total() + " of Rs 200000");
    }
}

Output:

In box: Rs 200000 of Rs 200000
Method Does
get() / set(v) read / write
incrementAndGet() ++x, atomically
getAndIncrement() x++, atomically
addAndGet(d) x += d, returns the new value
compareAndSet(expected, new) set only if the value is still expected

Use atomics for one shared number. When several fields must change together (cash and a sales log, seats and a booking list), use a lock around all of them.

Deadlock

Real-life example: the milk and the sugar. Ravi holds the milk and waits for the sugar; Asha holds the sugar and waits for the milk. Neither lets go.

record Jar(String name) {}
public class Main {
    static final Jar milk = new Jar("milk"), sugar = new Jar("sugar");

    static void cook(String who, Jar first, Jar second) {
        synchronized (first) {
            System.out.println(who + " has the " + first.name());
            try { Thread.sleep(100); } catch (InterruptedException e) { }
            synchronized (second) {
                System.out.println(who + " has the " + second.name() + ": chai!");
            }
        }
    }

    public static void main(String[] args) {
        new Thread(() -> cook("Ravi", milk, sugar)).start();
        new Thread(() -> cook("Asha", sugar, milk)).start();
    }
}

Output:

Asha has the sugar
Ravi has the milk
(still running after 8 seconds: stopped. The online compiler shows Time Limit Exceeded.)

A deadlock is when each thread holds a lock the other needs and waits for it forever. There's no error message: the program just stops moving (on the online compiler you see Time Limit Exceeded after 8 seconds; on a server it would hang forever).

A deadlock needs four things at once: locks that only one thread can hold, a thread that holds one lock while waiting for another, locks that can't be taken away, and a circle of waiting. Break any one and deadlock is impossible.

The fix: one lock order for everyone

record Jar(String name) {}
public class Main {
    static final Jar milk = new Jar("milk"), sugar = new Jar("sugar");

    static void cook(String who, Jar first, Jar second) {
        synchronized (first) {
            System.out.println(who + " has the " + first.name());
            try { Thread.sleep(100); } catch (InterruptedException e) { }
            synchronized (second) {
                System.out.println(who + " has the " + second.name() + ": chai!");
            }
        }
    }

    public static void main(String[] args) {
        new Thread(() -> cook("Ravi", milk, sugar)).start();
        new Thread(() -> cook("Asha", milk, sugar)).start();    // same order
    }
}

Output:

Ravi has the milk
Ravi has the sugar: chai!
Asha has the milk
Asha has the sugar: chai!

If everyone takes the locks in the same order, nobody can hold the second jar while waiting for the first, and the circle can't form. Other habits: hold as few locks as possible, for as short a time as possible, and never call unknown code while holding a lock.

Another tool, ReentrantLock.tryLock(timeout), lets a thread give up instead of waiting forever:

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    static final ReentrantLock milk = new ReentrantLock(), sugar = new ReentrantLock();

    static void cook(String who, ReentrantLock first, ReentrantLock second) {
        try {
            for (int attempt = 1; ; attempt++) {
                first.lock();
                try {
                    Thread.sleep(50);
                    if (second.tryLock(100, TimeUnit.MILLISECONDS)) {
                        try { System.out.println(who + " makes chai (attempt " + attempt + ")"); return; }
                        finally { second.unlock(); }
                    }
                } finally { first.unlock(); }
                Thread.sleep(who.equals("Ravi") ? 30 : 70);   // back off, then try again
            }
        } catch (InterruptedException e) { }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread r = new Thread(() -> cook("Ravi", milk, sugar));
        Thread a = new Thread(() -> cook("Asha", sugar, milk));
        r.start(); a.start(); r.join(); a.join();
        System.out.println("no deadlock: tryLock gave up and retried");
    }
}

Output:

Asha makes chai (attempt 2)
Ravi makes chai (attempt 3)
no deadlock: tryLock gave up and retried

volatile: seeing changes

Real-life example: the shutter nobody sees. The cook checked the shutter once, wrote "open" on his hand, and now only looks at his hand.

public class Main {
    static boolean closed = false;                // the shutter

    public static void main(String[] args) throws InterruptedException {
        Thread cook = new Thread(() -> {
            while (!closed) { }                   // keep making chai
            System.out.println("Cook saw the shutter, stopping");
        });
        cook.start();
        Thread.sleep(500);
        closed = true;
        System.out.println("Ravi: shutter down!");
        cook.join();
        System.out.println("Stall closed");
    }
}

Output:

Ravi: shutter down!
(still running after 8 seconds: stopped. The online compiler shows Time Limit Exceeded.)

To run fast, each thread may keep its own copy of a field (in a CPU register or cache), and the JIT (just-in-time compiler) may even read a field just once if the loop never changes it. main's write is real, but the cook never reads the real value: a visibility problem.

public class Main {
    static volatile boolean closed = false;       // the shutter

    public static void main(String[] args) throws InterruptedException {
        Thread cook = new Thread(() -> {
            while (!closed) { }                   // keep making chai
            System.out.println("Cook saw the shutter, stopping");
        });
        cook.start();
        Thread.sleep(500);
        closed = true;
        System.out.println("Ravi: shutter down!");
        cook.join();
        System.out.println("Stall closed");
    }
}

Output:

Ravi: shutter down!
Cook saw the shutter, stopping
Stall closed

A volatile field is always read from and written to main memory: every read sees the latest write by any thread.

volatile is not atomic

volatile only fixes visibility. total++ on a volatile field is still read, add, write:

public class Main {
    static volatile int total = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable cook = () -> {
            for (int i = 0; i < 1_000_000; i++) total++;
        };
        Thread a = new Thread(cook), b = new Thread(cook);
        a.start(); b.start(); a.join(); b.join();
        System.out.println("volatile total: " + total + " of 2000000");
    }
}

Output:

volatile total: 1546194 of 2000000
volatile synchronized / atomic
Every thread sees the latest value yes yes
Read-modify-write as one step no yes
Good for a flag one thread sets, others read counters, several fields changing together

Common mistakes (and what you see)

Mistake What you see Why Fix
total = total + amount; from two threads no error: the total is too low, different every run read, add, write interleave synchronized or AtomicInteger
lock milk → sugar in one thread, sugar → milk in another no error: frozen; Time Limit Exceeded deadlock: a circle of waiting take locks in one fixed order
static boolean closed; checked in a loop no error: the loop never ends; Time Limit Exceeded the thread keeps its own copy static volatile boolean closed;
static volatile int total; total++; no error: the total is still too low volatile is not atomic AtomicInteger.incrementAndGet()
synchronized on a different object in each thread no error: still races each lock has its own key all threads lock the same object

Mini project: train seat booking

Four booking agents share one train with 100 seats and send 160 requests. Checking seatsLeft == 0 and then decrementing must happen together inside one lock, or two agents can both see the last seat as free (a check-then-act race).

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

class Counter {
    private int seatsLeft;
    private final List<String> booked = new ArrayList<>();
    private final Object lock = new Object();
    Counter(int seats) { seatsLeft = seats; }

    boolean book(String who) {
        synchronized (lock) {              // check AND update together
            if (seatsLeft == 0) return false;
            seatsLeft--;
            booked.add(who);
            return true;
        }
    }
    int left() { synchronized (lock) { return seatsLeft; } }
    int bookedCount() { synchronized (lock) { return booked.size(); } }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter train = new Counter(100);           // 100 seats
        AtomicInteger refused = new AtomicInteger();
        List<Thread> agents = new ArrayList<>();
        for (int a = 1; a <= 4; a++) {
            String agent = "agent-" + a;
            Thread t = new Thread(() -> {
                for (int i = 0; i < 40; i++)        // 4 x 40 = 160 requests
                    if (!train.book(agent)) refused.incrementAndGet();
            });
            agents.add(t);
            t.start();
        }
        for (Thread t : agents) t.join();
        System.out.println("booked:  " + train.bookedCount());
        System.out.println("left:    " + train.left());
        System.out.println("refused: " + refused.get());
    }
}

Output:

booked:  100
left:    0
refused: 60

Practice

  1. Make an unsafe ticket counter, then fix it two ways.
  2. Write a deadlock with three locks, then fix it.
  3. A stop flag with and without volatile (episode code above).
  4. Explain why volatile int count; count++; is unsafe.
Solution 1

Unsafe:

public class Main {
    static int tickets = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable sell = () -> {
            for (int i = 0; i < 100_000; i++) {
                int now = tickets;
                Thread.yield();
                tickets = now + 1;
            }
        };
        Thread a = new Thread(sell), b = new Thread(sell);
        a.start(); b.start(); a.join(); b.join();
        System.out.println("unsafe: " + tickets + " of 200000");
    }
}

Output:

unsafe: 108709 of 200000

Fixed with synchronized:

public class Main {
    static int tickets = 0;

    static synchronized void sellOne() {    // static synchronized: locks Main.class
        int now = tickets;
        Thread.yield();
        tickets = now + 1;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable sell = () -> { for (int i = 0; i < 100_000; i++) sellOne(); };
        Thread a = new Thread(sell), b = new Thread(sell);
        a.start(); b.start(); a.join(); b.join();
        System.out.println("synchronized: " + tickets + " of 200000");
    }
}

Output:

synchronized: 200000 of 200000

Fixed with AtomicInteger:

import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static final AtomicInteger tickets = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Runnable sell = () -> { for (int i = 0; i < 100_000; i++) tickets.incrementAndGet(); };
        Thread a = new Thread(sell), b = new Thread(sell);
        a.start(); b.start(); a.join(); b.join();
        System.out.println("atomic: " + tickets.get() + " of 200000");
    }
}

Output:

atomic: 200000 of 200000
Solution 2

Three cooks in a circle: Ravi milk→sugar, Asha sugar→tea, Neha tea→milk.

record Jar(String name) {}

public class Main {
    static final Jar milk = new Jar("milk"), sugar = new Jar("sugar"), tea = new Jar("tea");

    static void cook(String who, Jar a, Jar b) {
        synchronized (a) {
            System.out.println(who + " holds " + a.name() + ", wants " + b.name());
            try { Thread.sleep(100); } catch (InterruptedException e) { }
            synchronized (b) { System.out.println(who + " used " + a.name() + " + " + b.name()); }
        }
    }

    public static void main(String[] args) {
        new Thread(() -> cook("Ravi", milk, sugar)).start();
        new Thread(() -> cook("Asha", sugar, tea)).start();
        new Thread(() -> cook("Neha", tea, milk)).start();
    }
}

Output:

Neha holds tea, wants milk
Ravi holds milk, wants sugar
Asha holds sugar, wants tea
(still running after 8 seconds: stopped. The online compiler shows Time Limit Exceeded.)

Fixed with one global order (milk, then sugar, then tea):

record Jar(String name) {}

public class Main {
    static final Jar milk = new Jar("milk"), sugar = new Jar("sugar"), tea = new Jar("tea");

    static void cook(String who, Jar a, Jar b) {
        synchronized (a) {
            try { Thread.sleep(100); } catch (InterruptedException e) { }
            synchronized (b) { System.out.println(who + " used " + a.name() + " + " + b.name()); }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // Deadlock version (a circle): Ravi milk->sugar, Asha sugar->tea, Neha tea->milk.
        // Fixed version below: one global order milk < sugar < tea, so every cook asks in that order.
        Thread r = new Thread(() -> cook("Ravi", milk, sugar));
        Thread a = new Thread(() -> cook("Asha", sugar, tea));
        Thread n = new Thread(() -> cook("Neha", milk, tea));   // was (tea, milk)
        r.start(); a.start(); n.start(); r.join(); a.join(); n.join();
        System.out.println("all done, no deadlock");
    }
}

Output:

Asha used sugar + tea
Ravi used milk + sugar
Neha used milk + tea
all done, no deadlock
Solution 3

See the FLAG and VOL programs in the volatile section: without volatile the cook never stops (Time Limit Exceeded); with volatile it stops right after "shutter down".

Solution 4

volatile guarantees that every read sees the latest write, but count++ is still three separate steps: read, add, write. Two threads can both read the same value and both write value + 1, losing one increment. Use AtomicInteger.incrementAndGet() or a synchronized method.

Quick quiz

Two threads each run count++ 100,000 times on static int count. Which change makes the total always correct?

A. static volatile int count B. increment an AtomicInteger instead C. call Thread.yield() after count++ D. use count = count + 1

Answer

B. volatile only makes changes visible; count++ is still read, add, write. yield and count + 1 change nothing. AtomicInteger.incrementAndGet() is one atomic step (a synchronized method would also work).

import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static final AtomicInteger count = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Runnable job = () -> { for (int i = 0; i < 100_000; i++) count.incrementAndGet(); };
        Thread a = new Thread(job), b = new Thread(job);
        a.start(); b.start(); a.join(); b.join();
        System.out.println(count.get());
    }
}

Output:

200000

Interview questions

  1. What is a race condition? A bug where the result depends on the timing/interleaving of threads, e.g. two threads doing x++ on the same field.
  2. Why is count++ not thread-safe? It's three operations (read, add, write) that other threads can interleave with.
  3. What does synchronized do? It makes a thread take an object's lock (monitor) before running the code, so only one thread runs that critical section at a time; it also guarantees visibility of changes made under the lock.
  4. synchronized method vs block? A method locks this (or the class for static) for the whole method; a block locks a chosen object for just a few lines.
  5. What is a deadlock and how do you avoid it? Threads each holding a lock the others need and waiting forever; avoid it with a fixed lock order, fewer/shorter locks, or tryLock with a timeout.
  6. What does volatile guarantee? Visibility (and ordering): reads see the latest write. It does not make compound actions like ++ atomic.
  7. When would you use AtomicInteger? For a single shared counter or value updated by many threads, without locks.
  8. Does Thread.sleep release a lock? No. A thread sleeping inside synchronized keeps the lock.
  9. What is a check-then-act race? Checking a condition (e.g. "a seat is free") and then acting on it in two steps; another thread can change it in between. Both steps must be in one lock.

Glossary

Term Meaning
Shared data a field or object that more than one thread reads or writes
Race condition a bug where the result depends on the timing of threads
Lost update one thread's write overwritten by another's
Read-modify-write read a value, change it, write it back: three steps, e.g. x++
Atomic done as one step that can't be interrupted or interleaved
Critical section code that must be run by only one thread at a time
Lock (monitor) the built-in key every Java object has; only one thread can hold it
synchronized method takes the lock of this (or of the class, if static) for the whole method
synchronized block takes the lock of a chosen object for a few lines
Lock object a private Object used only as a lock
BLOCKED the state of a thread waiting to take a lock
AtomicInteger an int whose updates (incrementAndGet, addAndGet) are atomic
Thread.yield() a hint to let another thread run now
Deadlock threads each holding a lock the other needs, waiting forever
Circular wait a circle of threads, each waiting for the next one's lock
Lock ordering everyone takes locks in the same fixed order, so no circle can form
ReentrantLock a lock object with extra features like tryLock(timeout)
Visibility whether one thread's write is seen by other threads
JIT compiler the just-in-time compiler that optimises hot code while the program runs
volatile a field always read from and written to main memory; fixes visibility, not atomicity
Check-then-act testing a condition then acting on it; must be done under one lock
Thread-safe correct even when used by many threads at once

Summary

  • Threads sharing data can race: x++ is read, add, write, and interleaved writes are lost.
  • synchronized takes an object's lock: one thread at a time runs the critical section. Keep it small; prefer a private lock object.
  • AtomicInteger gives atomic updates for a single shared number.
  • Deadlock: each thread holds what another needs. Take locks in one fixed order, hold them briefly, or use tryLock with a timeout.
  • volatile makes a change visible to all threads, e.g. a stop flag. It does not make ++ safe.
  • Next episode: executors, Future and CompletableFuture: a team of reusable threads instead of hiring one per job.