wait(), notify() and notifyAll() in Java: Inter-Thread Communication
wait(), notify() and notifyAll() are three methods of Object that implement inter-thread communication in Java: one thread waits until a condition becomes true, another thread announces that it has. You may call them only inside synchronized on the same object. wait() releases the object's monitor and puts the thread to sleep until it is signalled, notify() wakes up one of the waiting threads, notifyAll() wakes up all of them.
synchronized (lock) {
while (!ready) {
lock.wait(); // releases the monitor of lock and waits
}
// the condition holds - do the work
}
// in another thread
synchronized (lock) {
ready = true;
lock.notifyAll(); // wake up the waiting threads
} The compiler won't catch mistakes with these methods. lock.notify() outside synchronized compiles without a single warning and fails only at runtime with IllegalMonitorStateException. Using if instead of while around wait() is worse: it breaks the queue only once in a while, when a second thread manages to grab the monitor first (see Why wait() Is Called in a while Loop).
How wait(), notify() and notifyAll() Work
A thread that calls obj.wait() releases the monitor of obj and goes to sleep in that object's wait set. Another thread acquires the same monitor, changes the data and calls obj.notify() or obj.notifyAll(). The woken thread doesn't continue right away — only after it gets the monitor back.
The inter-thread communication mechanism in Java is built on wait(), notify() and notifyAll(). These methods are declared final in the Object class, so every class has them.
All three can be called only from a synchronized context, and it has to be synchronized on the same object whose method you call. What a monitor is and how synchronized acquires it is covered in Thread Synchronization in Java.
wait() makes the calling thread give up the monitor and suspend until some other thread enters the same monitor and calls notify() or notifyAll(). The thread also wakes up if it is interrupted via interrupt(), if the timeout of wait(ms) expires — and occasionally for no reason at all (more on that below). Before returning from wait(), the thread reacquires the monitor.
notify() wakes up one arbitrary thread among those waiting on this object. The JVM picks which one; the order in which threads called wait() doesn't matter. notify() itself doesn't release the monitor: the notifying thread finishes its synchronized block, and the woken thread sits in the BLOCKED state all that time (how it differs from WAITING is explained in Thread States in Java).
notifyAll() wakes up every thread that called wait() on the same object. They all wake up, but they get the monitor one at a time: the first runs its code and leaves synchronized, then the monitor goes to the next. That's why each awakened thread has to check the condition again — by its turn the condition may no longer hold.
| Method | What it does | Thread state | Edge cases |
|---|---|---|---|
wait() | Releases the monitor and waits for notify()/notifyAll() or interrupt() | WAITING | Without the monitor → IllegalMonitorStateException; on interrupt → InterruptedException; spurious wakeups possible |
wait(long timeout) | Same, but no longer than timeout milliseconds | TIMED_WAITING | wait(0) waits forever, like wait(); negative value → IllegalArgumentException |
wait(long timeout, int nanos) | Timeout plus extra nanoseconds | TIMED_WAITING | nanos outside 0–999999 → IllegalArgumentException; no real nanosecond precision |
notify() | Wakes up one arbitrary waiting thread | Caller stays RUNNABLE, the woken thread is BLOCKED until it gets the monitor | If nobody is waiting, nothing happens and the signal is lost |
notifyAll() | Wakes up all threads waiting on this object | All woken threads are BLOCKED and get the monitor in turn | Without the monitor → IllegalMonitorStateException, same as notify() |
IllegalMonitorStateException: Calling Outside synchronized
wait(), notify() and notifyAll() throw IllegalMonitorStateException when the current thread doesn't own the monitor of the object the method is called on. There are two ways to get there: calling the method with no synchronized at all, or synchronizing on one object and calling wait()/notify() on another.
public class MonitorOwnerExample {
public static void main(String[] args) {
Object lock = new Object();
Object other = new Object();
try {
lock.notify(); // outside synchronized
} catch (IllegalMonitorStateException e) {
System.out.println("1: " + e.getMessage());
}
synchronized (lock) {
try {
other.notify(); // we own the monitor of lock, not of other
} catch (IllegalMonitorStateException e) {
System.out.println("2: " + e.getMessage());
}
lock.notify(); // correct; nobody is waiting, so it does nothing
System.out.println("3: ok");
}
}
} 1: current thread is not owner
2: current thread is not owner
3: ok The text "current thread is not owner" comes from modern JDKs; in Java 8 this exception has no message, and getMessage() returns null. The second case shows up more often than you'd expect: the method is declared synchronized (monitor of this), but inside it calls queue.wait() on a field. The rule is simple: call wait() and notify() on the same object that sits in the parentheses of synchronized (…), and in a synchronized method call them on this — that is, plain wait() with no prefix.
Why the JVM insists on the monitor: checking the condition and going to sleep must be one indivisible step. Without the monitor, another thread could change the condition and call notify() exactly between the check and the call to wait(). The signal would go nowhere, and the thread would sleep forever.
Why wait() Is Called in a while Loop
wait() is always called inside a while loop that checks the condition, never inside an if. Returning from wait() doesn't guarantee the condition is true: the thread may have woken up without any notification (a spurious wakeup), or it was woken correctly but another thread grabbed the monitor first and changed the data.
A spurious wakeup is documented explicitly in Object.wait(): a thread can wake up even though nobody notified it, interrupted it, or let a timeout expire. It's a consequence of how waiting is implemented in operating systems, and the JavaDoc recommends exactly one idiom:
synchronized (obj) {
while (!condition) {
obj.wait();
}
// the action that needs the condition
} The second reason is more practical — a "stolen" condition. Take MyQueue from the example below and imagine get() says if (!valueSet) wait(); and there are two consumers. Consumer C1 waits on an empty queue. The producer puts a number and calls notify(); C1 wakes up but stays in BLOCKED. At that moment C2 grabs the monitor, sees valueSet == true, takes the number and clears the flag. Then C1 gets the monitor, falls through the if, and prints and returns the same number a second time, even though the queue is empty. With while, C1 rechecks valueSet, sees false and goes back to wait().
The MyQueue in this lesson uses while (!valueSet) and while (valueSet). That's correct for one consumer and for many.
Keep the condition in a field, not in the signal
notify() isn't remembered: if it fires while nobody is waiting yet, the signal is lost. So the event is always recorded in a field (valueSet, ready) that is changed under the same monitor, and the waiting thread checks the field first and only then calls wait(). A notification that arrives "too early" then breaks nothing: the thread sees true and doesn't wait at all.
Producer-Consumer Example with wait() and notify()
The producer consumer problem in Java is the classic use case for wait() and notify(): one thread puts data, another takes it, and neither should spin uselessly. In the example, MyQueue holds a single number: the producer waits until the slot is free, the consumer waits until a value appears. The valueSet field stores the condition, while wait() and notify() carry the signal.
Both Producer and Consumer are ordinary tasks that implement Runnable:
public class Producer implements Runnable {
private MyQueue myQueue;
public Producer(MyQueue myQueue) {
this.myQueue = myQueue;
}
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
myQueue.put(i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag and exit
}
}
} public class Consumer implements Runnable {
private MyQueue myQueue;
public Consumer(MyQueue myQueue) {
this.myQueue = myQueue;
}
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
myQueue.get();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag and exit
}
}
} public class MyQueue {
private int n;
private boolean valueSet = false;
public synchronized int get() throws InterruptedException {
while (!valueSet) {
wait();
}
System.out.println("Received: " + n);
valueSet = false;
notify();
return n;
}
public synchronized void put(int n) throws InterruptedException {
while (valueSet) {
wait();
}
valueSet = true;
this.n = n;
System.out.println("Sent: " + n);
notify();
}
} public class ProducerExample {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
Consumer consumer = new Consumer(myQueue);
Producer producer = new Producer(myQueue);
Thread t1 = new Thread(consumer);
Thread t2 = new Thread(producer);
t1.start();
t2.start();
}
} Output (shortened):
Sent: 0
Received: 0
Sent: 1
Received: 1
Sent: 2
Received: 2
...
Sent: 99
Received: 99 Unlike most multithreading examples, this output is the same on every run. Both lines are printed under the monitor, and the valueSet flag doesn't let the producer put the next number until the consumer has taken the previous one. Remove wait() and notify() together with the loops, and the lines get mixed up: some numbers are received twice, others are lost.
Why do get() and put() declare throws InterruptedException instead of catching it themselves? wait() throws it when the thread is interrupted and clears the interrupt flag. The older version with e.printStackTrace() inside the loop printed the stack trace and went straight back into wait(), so a thread that had been asked to stop kept waiting. Here the exception reaches run(), where the flag is restored and the loop ends. put() and take() in BlockingQueue work the same way; the general rules are in InterruptedException: How to Handle It.
notify() vs notifyAll(): Which One to Use
notify() is safe only when all waiting threads wait for the same condition and any of them can carry on. If threads with different conditions wait on one object (producers for "there's room", consumers for "there's data"), notify() can wake the wrong one and the program hangs. In that case you need notifyAll().
ProducerExample has one producer and one consumer: at any moment at most one thread is waiting, and notify() always wakes the right one. Add a second producer, and the very same MyQueue can stop forever:
| Step | What happens | Waiting in wait() |
|---|---|---|
| 1 | The slot is full. Producers P1 and P2 call put() and go into wait() | P1, P2 |
| 2 | Consumer C takes the number, notify() wakes P1 | P2 |
| 3 | C calls get() again: the slot is empty, C goes into wait(). P1 gets the monitor | P2, C |
| 4 | P1 puts a number, notify() wakes an arbitrary thread — say, P2 rather than C | C |
| 5 | P1 tries to put the next number: the slot is full — wait(). P2 gets the monitor: the slot is full — wait() | C, P1, P2 — nobody left to wake them |
No exception, the CPU is idle, the program just stands still. It's not a deadlock in the classic sense: the threads don't hold each other's monitors, they sit in WAITING for a signal nobody will send (for the real thing, see Deadlock in Java). The fix is to replace notify() with notifyAll() in both methods: at step 4 both P2 and C wake up, P2 rechecks the condition in while and goes back to sleep, and C takes the number.
The price of notifyAll() is extra wakeups: with a hundred waiting threads, all of them wake up and most immediately go back to sleep. Usually that's acceptable. If it isn't, you need separate wait sets for different conditions, which is what Condition gives you (see below).
wait(long timeout) and TIMED_WAITING
wait(long timeout) waits for a notification for no longer than the given number of milliseconds; meanwhile the thread is in the TIMED_WAITING state. The method returns nothing and doesn't tell you why it woke up — signal, timeout or spurious wakeup — so both the condition and the remaining time are checked in a loop.
For example, a get() with a timeout for MyQueue:
public synchronized int get(long timeoutMillis)
throws InterruptedException, TimeoutException {
long deadline = System.currentTimeMillis() + timeoutMillis;
while (!valueSet) {
long left = deadline - System.currentTimeMillis();
if (left <= 0) {
throw new TimeoutException("No data within " + timeoutMillis + " ms");
}
wait(left); // wait only for the remaining time
}
valueSet = false;
notifyAll();
return n;
} If you call wait(timeoutMillis) again with the original value after a spurious wakeup, the total wait stretches. Hence the recalculation of what's left. One more detail: wait(0) doesn't mean "don't wait", it means "wait with no limit".
wait(ms) shares only the TIMED_WAITING state with Thread.sleep(). sleep() keeps the monitor and doesn't wait for any signal; wait() releases the monitor and wakes up on notify(). The full comparison is in the table sleep() vs wait(). And if you need to wait not for an event but for another thread to finish, use Thread.join().
Modern Alternatives: BlockingQueue and Condition
In new code, producer-consumer is usually written without hand-rolled wait()/notify(): a BlockingQueue from java.util.concurrent (for example, new ArrayBlockingQueue<Integer>(1)) does what MyQueue does — put() waits for free space, take() waits for data, and the loop, the flag and the notifications are hidden inside.
When you need custom waiting logic, swap synchronized + wait()/notifyAll() for a ReentrantLock and its Condition objects. One lock can have several conditions (notFull, notEmpty), and signal() wakes only the threads waiting for the right one, so the "woke the wrong thread" problem from the notify() section goes away. The while rule around await() stays the same. You still need to understand wait()/notify(): older code is built on them, interviewers ask about them, and Condition follows the same pattern. Many JDK classes, such as the concurrent collections, are already thread-safe and do this coordination for you.
wait() and Virtual Threads
In Java 21–23, a virtual thread that calls wait() inside synchronized gets pinned to its carrier thread and occupies it for the entire wait. Java 24 fixed this (JEP 491): a virtual thread in Object.wait() unmounts from the carrier, just like in Thread.sleep() or while waiting on a ReentrantLock.
For wait() this matters more than for short synchronized blocks, because a wait can last indefinitely. If thousands of virtual threads on Java 21 wait for data in MyQueue, they tie up the carriers, and by default there are only as many carriers as CPU cores. On Java 21–23, prefer BlockingQueue or ReentrantLock with Condition for such queues; on Java 24 and later there's no need to rewrite wait()/notify() for the sake of virtual threads. More on pinning in synchronized and Virtual Threads.
Frequently Asked Questions
Why are wait() and notify() declared in Object and not in Thread?
Because a thread doesn't wait for another thread — it waits for the state of an object to change, and every object has a monitor. The wait set belongs to the monitor, so the methods that work with it belong to Object. A thread that calls wait() doesn't know who will wake it; any thread holding the same monitor can do it.
How do you stop a thread that is stuck in wait()?
Call interrupt() on it. wait() throws InterruptedException and clears the interrupt flag, so the handler must restore the flag or rethrow the exception, as in the producer-consumer example. Another option is to use wait(timeout) from the start, so the thread periodically checks whether it's time to quit.
Does wait() throw InterruptedException immediately after interrupt()?
Not immediately. The interrupted thread first has to reacquire the object's monitor, and only then does it leave wait() with the exception. If another thread holds the monitor at that moment, the interrupted one waits in BLOCKED. That's why a catch block inside a synchronized method always runs under the monitor.
Do I still need to learn wait() and notify() if java.util.concurrent exists?
Yes. New code usually replaces them with BlockingQueue, CountDownLatch or Condition, but plenty of existing code is built on wait()/notify(), and questions about while, spurious wakeups and notify vs notifyAll are a standard part of multithreading interviews. The high-level classes follow the same pattern; see Modern Alternatives.
Comments