Why threads need to wait for each other
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Threads often cannot go on until something happens in another thread: a token is ready, a result is published, a seat becomes free. The thread has to wait for that, and how it waits decides whether the computer stays fast or burns a whole CPU core doing nothing.
Busy waiting wastes the CPU
Busy waiting (also called spinning) means a thread checks a condition again and again in a tight loop, doing no useful work until the answer changes. A loop like while (!tokenReady) { } is busy waiting.
Example 1 · Busy waiting: asking again and again
import java.lang.management.ManagementFactory;import java.lang.management.ThreadMXBean;
public class BusyWaitDemo { static volatile boolean tokenReady = false;
public static void main(String[] args) throws InterruptedException { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); long[] checks = {0}; long[] cpuMs = {0};
Thread clerk = new Thread(() -> { try { Thread.sleep(100); // processing takes about 100 ms } catch (InterruptedException e) { return; } tokenReady = true; }, "clerk");
Thread student = new Thread(() -> { while (!tokenReady) { checks[0]++; // "Is my token ready?" again and again } cpuMs[0] = bean.getCurrentThreadCpuTime() / 1_000_000; }, "student");
clerk.start(); student.start(); student.join(); clerk.join();
System.out.println("Student checked the flag " + checks[0] + " times"); System.out.println("CPU time used by the student: " + cpuMs[0] + " ms"); }}Student checked the flag 94919993 times CPU time used by the student: 93 ms
What this code does
- The student thread runs
while (!tokenReady)with nothing inside except a counter. It asked about 95 million times in about 100 ms, and every one of those checks was useless except the last. - The CPU time is almost the same as the waiting time: the student kept one CPU core fully busy the whole time it waited. The numbers change from run to run and from machine to machine.
getCurrentThreadCpuTime()fromThreadMXBeanreports how much CPU time the current thread has used.tokenReadyisvolatileso the student is sure to see the change (the Visibility module explains why).
The loop never pauses, so the thread keeps one CPU core at 100% for the whole wait. On a laptop that means heat and battery drain. On a server it means other threads, such as the ones doing real work, get less CPU time.
volatile may loop forever. Even with volatile, busy waiting is correct but wasteful.A service-desk token counter as an analogy
You apply for a bank certificate at the service desk and get token 42. The certificate takes ten minutes. You can wait in three ways.
Example 2 · Polling with sleep: fewer checks, but late
public class PollingDemo { static volatile boolean tokenReady = false; static long readyAt;
public static void main(String[] args) throws InterruptedException { long[] checks = {0}; long[] noticedAt = {0};
Thread clerk = new Thread(() -> { try { Thread.sleep(100); } catch (InterruptedException e) { return; } readyAt = System.nanoTime(); // written before the volatile write tokenReady = true; }, "clerk");
Thread student = new Thread(() -> { try { while (!tokenReady) { checks[0]++; Thread.sleep(40); // walk back to the table, return after 40 ms } } catch (InterruptedException e) { return; } noticedAt[0] = System.nanoTime(); }, "student");
clerk.start(); student.start(); student.join(); clerk.join();
long lateMs = (noticedAt[0] - readyAt) / 1_000_000; System.out.println("Student checked the flag " + checks[0] + " times"); System.out.println("Student noticed the token about " + lateMs + " ms late"); }}Student checked the flag 3 times Student noticed the token about 28 ms late
What this code does
- Sleeping 40 ms between checks cuts the checks from millions to 3, and the CPU rests while the thread sleeps.
- The price is delay: the token was ready at about 100 ms, but the student only looked again at its next check, a little after 120 ms. A shorter sleep means less delay but more wasted checks, a longer sleep the opposite. The exact numbers change from run to run.
- Stand at the counter and keep asking "Is 42 ready?" every second. That is busy waiting: you tire yourself and block the queue.
- Sit down and walk to the counter every two minutes. That is polling: checking at fixed gaps, with a sleep in between. Fewer trips, but your certificate may sit there for up to two minutes.
- Sit down until the staff calls "Token 42". That is waiting to be notified: no wasted trips and no delay.
- Java threads have the same three choices. The third one is what Java's
wait()andnotifyAll()give you.
Waiting for a condition to become true
A condition is a true-or-false question about shared data that decides whether a thread may go on: "Is token 42 ready?", "Is there a free seat?", "Is the result published?". The thread waits while the answer is false.
Example 3 · Trap: checking again and again while holding the lock
class TokenBoard { private int readyToken = 0;
synchronized void markReady(int token) { readyToken = token; }
synchronized boolean isReady(int token) { return readyToken >= token; }}
public class SpinUnderLockDemo { public static void main(String[] args) throws InterruptedException { TokenBoard board = new TokenBoard();
Thread clerk = new Thread(() -> { board.markReady(42); System.out.println("Clerk: marked token 42 ready"); }, "clerk");
Thread student = new Thread(() -> { synchronized (board) { // takes the board's lock... clerk.start(); // the certificate is ready now long giveUpAt = System.currentTimeMillis() + 300; while (!board.isReady(42) && System.currentTimeMillis() < giveUpAt) { // ...and keeps checking while holding it } System.out.println("Student: gave up, token ready = " + board.isReady(42)); } }, "student");
student.start(); student.join(); clerk.join(); System.out.println("After both: token ready = " + board.isReady(42)); }}Student: gave up, token ready = false Clerk: marked token 42 ready After both: token ready = true
What this code does
- The clerk starts while the student holds the board's lock.
markReadyissynchronized, so the clerk needs that same lock and is stuck (stateBLOCKED) until the student gives up after 300 ms. - The student could never see
true: the only thread able to make the condition true was locked out by the waiting thread itself. Without the 300 ms limit this program would hang forever. - So a waiting thread needs two things at once: read the condition under the lock, but let go of the lock while it waits. The guarded block below does exactly that.
The condition reads shared data, so it must be checked while holding the lock that guards that data. That creates a trap: if the waiting thread keeps the lock while it checks again and again, the thread that would make the condition true can never get in.
The guarded block pattern
A guarded block is code that runs only once a condition (the guard) is true. Until then the thread waits without using the CPU and without holding the lock, and the thread that changes the data wakes it up.
synchronized (lock) { while (!condition) { // the guard lock.wait(); // sleep, let go of the lock } // the condition is true here: do the work}
// in the thread that changes the data:synchronized (lock) { // change the shared data lock.notifyAll(); // wake the waiting threads}Example 4 · A guarded block: wait without using the CPU
class TokenBoard { private int readyToken = 0; private int wakeUps = 0;
synchronized void waitFor(int token) throws InterruptedException { while (readyToken < token) { // the guard: "is my token ready yet?" wait(); // sleep and let go of the lock wakeUps++; } }
synchronized void markReady(int token) { readyToken = token; System.out.println("Clerk: token " + token + " ready"); notifyAll(); // wake every thread waiting on this board }
synchronized int wakeUps() { return wakeUps; }}
public class GuardedBlockDemo { public static void main(String[] args) throws InterruptedException { TokenBoard board = new TokenBoard();
Thread student = new Thread(() -> { System.out.println("Student: waiting for token 42"); try { board.waitFor(42); } catch (InterruptedException e) { return; } System.out.println("Student: collected token 42"); }, "student");
Thread clerk = new Thread(() -> { try { Thread.sleep(100); board.markReady(41); Thread.sleep(100); board.markReady(42); } catch (InterruptedException e) { return; } }, "clerk");
student.start(); clerk.start(); Thread.sleep(50); System.out.println("Student state while waiting: " + student.getState());
student.join(); clerk.join(); System.out.println("Student woke up " + board.wakeUps() + " times"); }}Student: waiting for token 42 Student state while waiting: WAITING Clerk: token 41 ready Clerk: token 42 ready Student: collected token 42 Student woke up 2 times
What this code does
- While its token is not ready, the student calls
wait(). It sleeps in theWAITINGstate, uses no CPU and lets go of the board's lock, so the clerk can get in. - Each
markReadychanges the state and callsnotifyAll(). The student wakes up, takes the lock back and checks the guard again: after token 41 it is still false, so it waits again; after token 42 it is true and the loop ends. - Two wake-ups instead of millions of checks, and the student reacts at once instead of up to 40 ms late. The order of the first lines and the wake-up count can differ on a very busy machine, so the output is labelled a sample.
- The waiting side checks the guard under the lock and calls
wait()while it is false. - The changing side updates the data under the same lock and calls
notifyAll(). - A woken thread takes the lock back and checks the guard again, which is why it is a
whileloop. - The next lesson, wait and notify, explains each of these rules and what breaks when one is missing.
Order of execution
One full wait and notify
Put the steps of the guarded block in the order they happen.
Next step
Check your understanding
12 quick questions