CKTIS / Java
Object.wait() and Object.notifyAll(): waiting for a condition
Guard shared state with one monitor, recheck the condition in a `while` loop, and remember that `notifyAll()` neither releases the lock nor hands it to a waiter.
Version: Java SE 21
Syntax
java.lang.Object instance methods (Java SE 21):
public final void wait() throws InterruptedException
public final void wait(long timeoutMillis) throws InterruptedException
public final void wait(long timeoutMillis, int nanos) throws InterruptedException
public final void notifyAll()
public final void notify()
Waiting thread: synchronized (lock) { while (!ready) { lock.wait(); } }
Signalling thread: synchronized (lock) { ready = true; lock.notifyAll(); }Object.wait/notifyAll is shorthand for two operations on an object's intrinsic monitor. wait(), notifyAll(), and notify() are instance methods of java.lang.Object. Call them on the same lock object whose monitor the current thread owns, for example inside synchronized (lock). Holding another object's monitor is not enough: calling without owning the receiver's monitor throws IllegalMonitorStateException.
If the current thread owns lock's monitor and its interrupt status is already set when it calls lock.wait(), the method clears that status and throws InterruptedException without adding the thread to the wait set or releasing the monitor. Otherwise, lock.wait() adds the current thread to lock's wait set and releases only that monitor, at every reentrant level. Other monitors remain held. The waiting thread must reacquire that monitor at its previous lock depth before wait() returns or throws because the wait was interrupted. notifyAll() wakes all threads in that wait set; notify() chooses one arbitrarily if any are waiting. Neither method releases or hands off the lock, and neither saves a notification for future waiters. Awakened threads compete for the monitor once it is released, with no guaranteed order.
Read and change shared state under the same monitor. After changing it, call notifyAll() before releasing the lock. Use while (!ready) { lock.wait(); }, not if: a thread can wake spuriously, or another thread can change the condition before the waiter reacquires the monitor. A notification is a reason to check again, not proof the condition is true. Releasing and later acquiring the same monitor makes the protected changes visible.
wait() has no timeout. wait(long timeoutMillis) takes milliseconds, and wait(long timeoutMillis, int nanos) also takes extra nanoseconds from 0 to 999999. All-zero arguments mean no timeout; negative milliseconds or out-of-range nanoseconds cause IllegalArgumentException. For a timeout that covers the entire loop, recompute the remaining time. When wait() throws InterruptedException, it clears the interrupt status. Propagate the exception, or restore the status if you stop the operation without propagating it.
Examples
public final class WaitNotifyDemo {
private final Object lock = new Object();
private boolean ready;
private void makeReady() {
synchronized (lock) {
ready = true;
lock.notifyAll();
}
}
private void runDemo() throws InterruptedException {
Thread publisher = new Thread(this::makeReady);
synchronized (lock) {
publisher.start();
while (!ready) {
lock.wait();
}
}
publisher.join();
System.out.println("ready");
}
public static void main(String[] args) throws InterruptedException {
new WaitNotifyDemo().runDemo();
}
}Result
ready
The main thread starts the publisher while holding `lock`. The publisher cannot set `ready` until `wait()` releases that monitor. After reacquiring it, the main thread checks the condition again. The program prints one line: `ready`.
Related lessons
- Java · Lesson 28 · Advanced · Version: 2