← Course Map M3: Thread Lifecycle & Monitors — Weeks 2–3
MODULE 03 · WEEKS 2–3 · PROTOTYPE MODULE

Thread Lifecycle & Monitor Coordination

Picture a small restaurant counter guarded by one Key. Once you see how threads move between the Hallway (BLOCKED), the Counter (holding the Key), and the Bench (WAITING), wait(), notifyAll(), and Producer-Consumer bugs stop feeling mysterious.

Key = object lock Hallway = BLOCKED (Entry Set) Bench = WAITING (Wait Set) Bell = notify / notifyAll Timer = TIMED_WAITING

The core idea: Every Java thread is always in one of 6 exact states. Locking a shared counter with synchronized keeps two threads from colliding, but when a Chef finds the counter empty, it must drop the Key and sit on the Bench (wait()) until a Waiter adds food and rings the Bell (notifyAll()).

Use Exam Cram in the top bar right before tests to hide long walkthroughs and keep tight recaps, diagrams, exam traps, and the comparison table.

Exam Cram Mode is ON: Analogies, free-play controls, and raw logs are hidden — showing only section recaps, diagrams, exam traps, comparison table, and self-test drills.

1. The Six States of a Java Thread

Thread.State
Recap: NEW (before start()), RUNNABLE (ready/running), BLOCKED (Hallway: waiting for a synchronized Key), WAITING (Bench: wait()/join()), TIMED_WAITING (Timer: sleep(ms)/wait(ms)/join(ms)), TERMINATED (done). Notified threads re-enter BLOCKED before RUNNABLE. Calling start() on any non-NEW thread throws IllegalThreadStateException.
Everyday Model · One Shift, Six States

A thread is like a kitchen worker: hired but not clocked in (NEW), working on the floor (RUNNABLE), stuck in the Hallway waiting for the Key (BLOCKED), resting on the Bench waiting for the Bell (WAITING), on a Timer pause (TIMED_WAITING), or clocked out for good (TERMINATED).

The distinction tested most often is BLOCKED vs WAITING. BLOCKED means a thread is waiting in the for a synchronized Key. WAITING means it paused indefinitely via wait() (sitting in the ) or via join().

Interactive 6-State Java Thread Lifecycle

Click any state box to inspect transitions & Key rules
start() done needs Key gets Key wait()/join() join() ends sleep/wait(ms) sleep ends notify: re-lock wait(ms) wakes: re-lock NEW Not clocked in RUNNABLE Ready or Running TERMINATED Shift finished BLOCKED Hallway (Entry Set) Waiting for Key WAITING Bench (Wait Set) wait() · join() TIMED_WAITING Timer pause sleep/wait/join(ms) Single-start rule Calling start() on any thread not in NEW (even while RUNNABLE) → throws IllegalThreadStateException
RUNNABLE

Ready or actively running on a CPU core

Entered after start(). Java merges "Ready" (in the OS scheduler queue) and "Running" (on CPU) into one state: RUNNABLE.

Entered via: start(), lock acquired, sleep/join ends Exits to: BLOCKED / WAITING / TIMED_WAITING / TERMINATED
Observation rule (Week 3 Tutorial Q1): Use getState() strictly for debugging and observation — never for synchronization decisions, because a thread's state can change immediately after getState() returns.
Lecture Shorthand vs. Actual JVM Behavior
Lecture 3's quick-reference diagram uses shorthand showing WAITING → RUNNABLE on notify(). What the JVM actually does (and what Lecture 2 notes explicitly) is WAITING → BLOCKED (Hallway, competing to re-acquire the Key) → RUNNABLE once it wins the Key again. Mentioning that middle BLOCKED step is strong Level-6 detail.
Quick Check · 5 Seconds

You call worker.start() a second time while worker is still running (or after it finishes). What does the JVM do?

start() is only valid while a thread is in NEW. Calling it on a RUNNABLE, WAITING, or TERMINATED thread always throws IllegalThreadStateException. Instantiate a new Thread instead.

2. Lab 1: Predict KitchenWorker Step by Step

Week 3 Tutorial Q1
Recap: worker.getState() is deterministic before start() (NEW) and after join() (TERMINATED), but timing-dependent right after start() and after Thread.sleep(500). While main executes worker.join(), main is WAITING and worker stays TIMED_WAITING until its 2000 ms sleep ends.
How to use this lab: Before each step, predict what state worker and main will be in, then click Check & Step →. Toggle Slow CPU to see why Lines 4 and 6 can vary across runs (Tutorial Q1 Task 2).

Interactive Tracer: LifecycleDemo + KitchenWorker

Before Step 1: predict both states after Line 1 runs Predictions: 0 / 0
LifecycleDemo.java (our completion of Q1) Step 0 / 9
1KitchenWorker worker = new KitchenWorker();
2System.out.println(worker.getState());
3worker.start();
4System.out.println(worker.getState());
5Thread.sleep(500); // main naps 500 ms
6System.out.println(worker.getState());
7worker.join(); // main waits for worker
8System.out.println(worker.getState());
9// worker.start(); // IllegalThreadStateException
KitchenWorker.java (run()) 2000 ms pause
1public void run() {
2 System.out.println("Preparing...");
3 try {
4 Thread.sleep(2000);
5 } catch (InterruptedException e) {
6 Thread.currentThread().interrupt();
7 return;
8 }
9 System.out.println("Order completed");

Live JVM Thread States

worker (KitchenWorker) Not created yet
—
main (Main Thread) Ready to start main()
RUNNABLE
Pick a prediction above (optional) and click Check & Step → to trace both threads together.
Show console trace log
[console] Ready to trace LifecycleDemo.main()...
Why can Lines 4 and 6 vary? A 500 ms sleep gives the worker time to enter Thread.sleep(2000), but the OS scheduler makes no guarantee. Toggle Slow CPU above to see Line 6 catch worker still in RUNNABLE.
Exam Trap (Week 3 Tutorial Q1): At Step 7a (~500 ms), main calls worker.join() while worker still has ~1500 ms left in Thread.sleep(2000). main enters WAITING, while worker stays in TIMED_WAITING until its Timer ends.

3. Unified Lab: Inside the Monitor & OrderCounter

Week 3 Tutorial Q2
Recap: Monitor rooms in order: Hallway (Entry Set · BLOCKED) → Counter (Key Owner) → Bench (Wait Set · WAITING). wait() drops the Key and resumes on the next line — so if skips rechecking and lets a second Chef call poll() on an empty queue (Preparing: null). With 2 Waiters + 2 Chefs sharing one Bench, notify() wakes an arbitrary sleeper and can cause a lost wake-up hang (all threads WAITING). Always use while + notifyAll().
Everyday Model · One Board for Everything

Every has the same 3 rooms from left to right: the Hallway (BLOCKED — waiting for the Key), the Counter (holding the Key), and the Bench (WAITING — dropped the Key via wait()). Watch the thread chips pinned to the Java code on the right to see which line each thread resumes on.

Unified OrderCounter Monitor Board + Pinned Code Lines

StartPick Story 0 to watch how the Key, Hallway, Bench, and sleep() trap work — then try Story 1 ("You are the JVM") and Story 2 (pinned if vs while lines).
Free play (arbitrary wakeup on notify):
Shared Queue (orders, cap=1):
empty

1. Hallway (Entry Set · BLOCKED)

Hallway empty

2. Counter (Key Owner)

Key is free

3. Bench (Wait Set · WAITING)

Bench empty
takeOrder() — where each Chef is paused while + notifyAll()
1public synchronized String takeOrder() {
2 while (orders.isEmpty()) {
3 wait(); // resumes on NEXT line
4 }
5 String o = orders.poll();
6 notifyAll();
7 return o; // exits & drops Key
placeOrder() — where each Waiter is paused Same Counter Key
1public synchronized void placeOrder(o) {
2 while (orders.size() == CAPACITY) {
3 wait(); // resumes on NEXT line
4 }
5 orders.add(o);
6 notifyAll();
7} // exits & drops Key
Show event log
[monitor] Ready.
Note on 1 Waiter + 1 Chef: Week 2 Tutorial's 1-Producer, 1-Consumer code is safe with notify() because all waiting threads have the same role (Lecture 2: "use only when all waiters are equivalent"). As soon as 2+ roles share one Bench, notify() risks a lost wake-up hang — switch to notifyAll() (or separate ReentrantLock Conditions in Module 4).
Quick Check · 5 Seconds

Chef-1 acquires the Counter Key, then calls Thread.sleep(2000) inside synchronized takeOrder(). What happens to the Key?

Thread.sleep() never releases any monitor lock. While Chef-1 is in TIMED_WAITING, Waiters attempting to enter placeOrder() sit in the Hallway in state BLOCKED.

4. Java Code, Translated into Plain English

Lecture 2 & 3
Recap: Four rules — (1) call wait/notifyAll only while holding that object's lock (else IllegalMonitorStateException), (2) always wait in a while loop, (3) prefer notifyAll() on a shared Bench, (4) keep slow work (sleep/I/O) outside synchronized.

Broken vs Fixed OrderCounter.takeOrder()

OrderCounter.java (Broken) Can return null or cause a lost wake-up hang
public synchronized String takeOrder() Acquire this Counter's Key
        throws InterruptedException {
    if (orders.isEmpty()) { Bug: checks once; never rechecks after wakeup
        wait(); Drop Key & sit on Bench; resume on next line
    }
    String order = orders.poll(); Returns null if another Chef took last order
    notify(); Bug: wakes 1 arbitrary sleeper (may be same role)
    return order; Exit method & release Key
}
Two failure modes: (1) After a or another Chef grabbing the last item, if does not recheck and orders.poll() returns null (Preparing: null); (2) With 2 Waiters + 2 Chefs, notify() can wake a same-role thread and leave all threads stuck in WAITING.

Keep slow work (sleep / cooking) outside synchronized

Anti-pattern — holds Key for 300 ms Waiters sit BLOCKED in Hallway
public synchronized String takeOrder() throws InterruptedException {
    while (orders.isEmpty()) wait();
    String order = orders.poll();
    Thread.sleep(300); // Holds Counter Key while cooking!
    notifyAll();
    return order;
}
Result: Waiters stay BLOCKED in the Hallway for 300 ms even though the queue itself only needed microseconds.

5. Clean Shutdowns: SingleSlotMailBox

Week02ThreeTry.zip
Recap: In SingleSlotMailBox, consume() retries wait(500) 3 times; when attempts >= 3, it calls stop() (setting stopped = true + notifyAll()) before throwing TimeoutException. Because Producer sleeps 5000 ms, the timeout path wins — Main's poison pill produce(-1) never gets consumed.
Two Alternative Shutdown Paths (Only One Fires Per Run)

Week02ThreeTry.zip implements two polite ways to close the mailbox without deprecated Thread.stop(): if the Producer finishes normally, Main drops a (-1); if the Producer is too slow, the Consumer times out after 3 × 500 ms and calls stop() first.

Predict the Output · Week02ThreeTry.zip

In Producer.java, the Producer sleeps 5000 ms after producing item 1. In SingleSlotMailBox.consume(), the Consumer gives up after 3 × wait(500) (~1.5 s). Does Main's poison pill mailBox.produce(-1) ever reach the Consumer?

After consuming item 1 (and sleeping 500 ms), Consumer loops back while Producer is still sleeping 5000 ms. Three wait(500) retries expire (~1.5 s), so Consumer calls stop() (setting stopped = true) and exits on TimeoutException. When Producer later checks if (box.isStopped()) break; and Main calls mailBox.produce(-1), produce() sees if (stopped) return false; — the -1 is never placed or consumed.

Exact Order in SingleSlotMailBox.consume() on Timeout

stop() runs before throw TimeoutException
1. Empty Slot !availability && !stopped wait(500) → TIMED 2. Three Retries attempts: 0 → 1 → 2 → 3 Producer still sleeps 5 s 3. Call stop() stopped = true notifyAll() 4. Throw TimeoutException Consumer breaks Why does stop() call notifyAll() before throwing? If the Producer were parked on the Bench while the slot was full, notifyAll() wakes it to recheck !stopped and exit cleanly.
Deprecated methods to avoid (Lecture 3): Never use Thread.stop(), suspend(), or resume() — they can leave shared objects corrupted or Keys permanently held.

6. Exam Ledger: Monitor & Thread Methods

Exam Table

wait() vs notify()/notifyAll() vs sleep() vs join()

Know which require the Key and which drop it
Method Defined On Must Hold Lock? Releases Lock? Thread State & Wakeup
obj.wait() Object YES (else IllegalMonitorStateException) YES — releases only obj's Key WAITING → notify/notifyAll → BLOCKED (re-lock) → RUNNABLE.
obj.wait(ms) Object YES (else IllegalMonitorStateException) YES — releases only obj's Key TIMED_WAITING → Bell or Timer → BLOCKED (re-lock) → RUNNABLE.
obj.notify() / notifyAll() Object YES (else IllegalMonitorStateException) NO — keeps Key until leaving synchronized Caller stays RUNNABLE; woken thread(s) move from Bench → Hallway (BLOCKED).
Thread.sleep(ms) Thread (static) No NO — keeps all held Keys TIMED_WAITING → Timer ends or interrupt() → RUNNABLE.
t.join() Thread No Does not release unrelated Keys WAITING (the caller!) until target thread t reaches TERMINATED.

7. Exam Trace Checks

Self-Test
Fresh on every visit so you can genuinely re-test yourself. This run: 0 / 3 · Best: 0 / 3
Exam Check 1 · Thread States (Week 3 Tutorial Q1)

At ~500 ms in LifecycleDemo, worker is inside Thread.sleep(2000) and main calls worker.join() (no timeout). What are both states right then?

Walkthrough: main called join() with no timeout, so main enters WAITING until worker terminates. Meanwhile worker still has ~1500 ms left in Thread.sleep(2000), so worker is in TIMED_WAITING. Neither thread is competing for a monitor Key, so neither is BLOCKED.
Exam Check 2 · Monitor Key Trap

Chef-1 enters synchronized takeOrder() and calls Thread.sleep(2000). Waiter-1 calls synchronized placeOrder("Burger") on the same OrderCounter. What state does Waiter-1 enter?

Walkthrough: Both synchronized instance methods share the same this monitor Key. Because Thread.sleep() never releases any lock, Chef-1 keeps the Key while sleeping in TIMED_WAITING, forcing Waiter-1 into the Hallway (Entry Set) in state BLOCKED.
Exam Check 3 · Can This Hang?

A 1-slot OrderCounter has 2 Waiters and 2 Chefs. Both methods use while loops, but call notify() instead of notifyAll(). Which statement is true?

public synchronized void placeOrder(String o) throws InterruptedException {
    while (orders.size() == 1) wait();
    orders.add(o);
    notify();
}
Walkthrough: All Waiters and Chefs share one Bench (Wait Set), and notify() wakes one arbitrary sleeper. If Chef-1 consumes and wakes Chef-2 (instead of a Waiter), Chef-2 rechecks while (orders.isEmpty()) and goes back to the Bench. All 4 threads end up in WAITING — a lost wake-up hang (often loosely called deadlock, though no lock cycle exists). Fix: use notifyAll().

8. Module 3 Mastery Checklist

Saved locally

Tick off each skill once you can explain it aloud from memory (syncs to your Course Map).