Skip to lesson

Thread coordination: common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Thread coordination bugs rarely crash on the first run. A program hangs once a week, a count goes to -1 under load, or the JVM refuses to exit. Most of them come from a handful of mistakes, and each has a short, reliable fix.

Mistake 1: if instead of while around wait

if (condition is false) wait(); checks once. After waking, the thread acts even if another thread got there first, if notifyAll() was meant for someone else, or after a spurious wakeup.

Example 1 · Mistake: if around wait lends one laptop twice

IfAroundWaitDemo.javaJava
class LaptopDesk {    private int laptops = 0;    private int lent = 0;
    synchronized void borrow(boolean useWhile) throws InterruptedException {        if (useWhile) {            while (laptops == 0) {                wait();            }        } else if (laptops == 0) {            wait();        }        laptops--;        lent++;        notifyAll();    }
    synchronized void giveBack() {        laptops++;        notifyAll();    }
    synchronized int lent() { return lent; }    synchronized String report() { return "lent " + lent + ", laptops left " + laptops; }}
public class IfAroundWaitDemo {    static void run(String label, boolean useWhile) throws InterruptedException {        LaptopDesk desk = new LaptopDesk();        Thread[] students = new Thread[2];        for (int i = 0; i < 2; i++) {            students[i] = new Thread(() -> {                try {                    desk.borrow(useWhile);                } catch (InterruptedException e) {                    return;                }            }, "student-" + (i + 1));            students[i].start();        }        for (Thread s : students) {              // demo only: both must be waiting            while (s.getState() != Thread.State.WAITING) {                Thread.sleep(5);            }        }
        desk.giveBack();                         // ONE laptop comes back        if (useWhile) {            while (desk.lent() == 0) {           // demo only: wait for the first loan                Thread.sleep(5);            }            for (Thread s : students) {                s.interrupt();            }        }        for (Thread s : students) {            s.join();        }        System.out.println(label + desk.report());    }
    public static void main(String[] args) throws InterruptedException {        run("With if:    ", false);        run("With while: ", true);    }}
Output
With if:    lent 2, laptops left -1
With while: lent 1, laptops left 0

What this code does

  • One laptop comes back and notifyAll() wakes both waiting students. With if, both skip the check and borrow, so one laptop is lent twice and the count becomes -1.
  • With while, the second student checks again, sees 0 laptops and goes back to waiting until main interrupts it. The two "demo only" loops just make the run repeatable.

Counts go negative, queues are read when empty, and the same item is handed out twice.

The fix is always the same: while (!condition) wait();. The thread checks again after every wake-up and waits again if the condition is still false.

Mistake 2: calling notify without the lock

wait, notify and notifyAll must be called while holding the lock of the same object. A notifyAll() placed after the synchronized block, or called on a different object than the one locked, throws IllegalMonitorStateException at run time, and the waiting thread is never woken.

Example 2 · Mistake: notifyAll outside the lock

NotifyWithoutLockDemo.javaJava
class ResultBoard {    private String result;
    void publishWrong(String r) {        synchronized (this) {            result = r;        }        notifyAll();                       // lock already released    }
    synchronized void publishRight(String r) {        result = r;        notifyAll();    }
    synchronized String await() throws InterruptedException {        while (result == null) {            wait();        }        return result;    }}
public class NotifyWithoutLockDemo {    static void run(String label, boolean right) throws InterruptedException {        ResultBoard board = new ResultBoard();        String[] got = new String[1];        Thread student = new Thread(() -> {            try {                got[0] = board.await();            } catch (InterruptedException e) {                return;            }        }, "student");        student.setDaemon(true);                 // so a stuck student cannot keep the demo alive        student.start();        while (student.getState() != Thread.State.WAITING) {   // demo only: let it reach wait()            Thread.sleep(5);        }
        try {            if (right) {                board.publishRight("Roll 7: 91");            } else {                board.publishWrong("Roll 7: 91");            }            System.out.println(label + "publish finished");        } catch (IllegalMonitorStateException e) {            System.out.println(label + "publish threw " + e.getClass().getSimpleName());        }        student.join(500);        System.out.println(label + "student got: " + got[0]);    }
    public static void main(String[] args) throws InterruptedException {        run("Wrong: ", false);        run("Right: ", true);    }}
Output
Wrong: publish threw IllegalMonitorStateException
Wrong: student got: null
Right: publish finished
Right: student got: Roll 7: 91

What this code does

  • publishWrong calls notifyAll() after its synchronized block has ended, so it throws IllegalMonitorStateException. The result is stored, but the student is asleep in wait() and nobody wakes it: after 500 ms it still has nothing (it is a daemon thread only so the demo can end).
  • Two failures from one misplaced line: the publisher crashes and the waiter is stuck. Keep the change and the notifyAll() together inside one synchronized block or method.

Keep the change and the notify together: change the shared data and call notifyAll() inside the same synchronized block or method. Inside synchronized (lock), write lock.wait() and lock.notifyAll(), not plain wait().

Mistake 3: workers that never stop

A worker blocked in take() waits forever unless something wakes it. Non-daemon workers stuck like this keep the JVM alive, so the program never exits even after main has finished.

Example 3 · Mistake: one pill for three workers

NeverStopDemo.javaJava
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class NeverStopDemo {    static final String POISON = new String("POISON");
    static void run(String label, int pills) throws InterruptedException {        BlockingQueue<String> jobs = new ArrayBlockingQueue<>(10);        String[] endedBy = new String[3];        Thread[] workers = new Thread[3];        for (int w = 0; w < 3; w++) {            int idx = w;            workers[w] = new Thread(() -> {                try {                    while (jobs.take() != POISON) {                        // handle the job                    }                    endedBy[idx] = "pill";                } catch (InterruptedException e) {                    endedBy[idx] = "interrupt";                }            }, "worker-" + (w + 1));            workers[w].start();        }
        for (int i = 1; i <= 6; i++) {            jobs.put("JOB-" + i);        }        for (int p = 0; p < pills; p++) {            jobs.put(POISON);        }
        // demo only: wait until every worker has either finished or is stuck in take()        while (true) {            int settled = 0;            for (Thread t : workers) {                Thread.State s = t.getState();                if (s == Thread.State.TERMINATED || (s == Thread.State.WAITING && jobs.isEmpty())) {                    settled++;                }            }            if (settled == 3) {                break;            }            Thread.sleep(5);        }        int stuck = 0;        for (Thread t : workers) {            if (t.isAlive()) {                stuck++;            }            t.interrupt();                  // rescue the stuck ones so the demo ends            t.join();        }        int byPill = 0;        for (String e : endedBy) {            if (e.equals("pill")) {                byPill++;            }        }        System.out.println(label + "stuck in take(): " + stuck + ", stopped by a pill: " + byPill);    }
    public static void main(String[] args) throws InterruptedException {        run("1 pill:  ", 1);        run("3 pills: ", 3);    }}
Output
1 pill:  stuck in take(): 2, stopped by a pill: 1
3 pills: stuck in take(): 0, stopped by a pill: 3

What this code does

  • With one pill, one worker stops and the other two block in take() forever. They are normal (non-daemon) threads, so in a real program the JVM would never exit; here main rescues them with interrupt().
  • With one pill per worker, all three stop by themselves after the 6 jobs. The getState() loop only waits for things to settle so the counts are the same on every run.

The usual causes: no stop signal at all, fewer poison pills than workers, or a volatile flag that a blocked worker never gets to check.

Fix it with one pill per consumer, sent after every producer has finished, or with interrupt() when you need to stop at once (then drainTo the leftovers).

Mistake 4: changing the state without notifying

Every method that changes something a thread might wait for must call notifyAll().

Check each synchronized method that writes a field used in a guard: does it notify? And check each waiter: does it wait on a stored condition, never on "a notify"?

Example 4 · Mistake: changing the state without notifying

ForgotNotifyDemo.javaJava
class TicketCounter {    private boolean paid = false;
    void markPaidNoNotify() {        synchronized (this) {            paid = true;                    // forgot notifyAll()        }    }
    synchronized void markPaid() {        paid = true;        notifyAll();    }
    // Waits at most timeoutMs; returns how long it actually waited.    synchronized long awaitPaid(long timeoutMs) throws InterruptedException {        long start = System.currentTimeMillis();        long deadline = start + timeoutMs;        while (!paid) {            long left = deadline - System.currentTimeMillis();            if (left <= 0) {                break;            }            wait(left);        }        return System.currentTimeMillis() - start;    }}
public class ForgotNotifyDemo {    static void run(String label, boolean notify) throws InterruptedException {        TicketCounter counter = new TicketCounter();        long[] waited = new long[1];        Thread printer = new Thread(() -> {            try {                waited[0] = counter.awaitPaid(400);            } catch (InterruptedException e) {                return;            }        }, "ticket-printer");        printer.start();        while (printer.getState() != Thread.State.TIMED_WAITING) {   // demo only            Thread.sleep(5);        }
        if (notify) {            counter.markPaid();        } else {            counter.markPaidNoNotify();        }        printer.join();        System.out.println(label + "printer waited the full 400 ms? " + (waited[0] >= 350));    }
    public static void main(String[] args) throws InterruptedException {        run("No notifyAll:   ", false);        run("With notifyAll: ", true);    }}
Output
No notifyAll:   printer waited the full 400 ms? true
With notifyAll: printer waited the full 400 ms? false

What this code does

  • Without notifyAll(), the payment is stored but nobody wakes the printer. It notices only when its 400 ms timeout ends; with a plain wait() and no timeout, it would sleep forever.
  • Every method that changes something a thread may wait for must call notifyAll() under the same lock. With the fix, the printer wakes at once.

A setter that updates the field but forgets to notify leaves waiting threads asleep, and a notify sent before anyone waits is lost if the waiter does not check a stored condition first. With a BlockingQueue both checks are done for you.

Finish up

Mark complete & continue

Next: ReentrantLock and unlock in finally