wait / notify
wait parks the current thread and releases the monitor it holds. notify/notifyAll wakes waiters on that same monitor. You must call them inside synchronized and you must loop on the condition.
Detailed Explanation
A producer fills a buffer. A consumer should sleep while the buffer is empty, not spin. Object.wait is that sleep, tied to a monitor. The consumer locks, sees "empty", and calls wait. Wait releases the lock and parks. The producer locks, adds an item, calls notifyAll, and unlocks. The consumer wakes, reacquires the lock, and must check the condition again.
The loop is mandatory. Wakes happen for four reasons: notify, notifyAll, a spurious wakeup (allowed by the spec), or interruption. The buffer may also be empty again because another consumer ran first. if (empty) wait() is a bug. while (empty) wait() is the pattern.
notify wakes one waiter. notifyAll wakes all. Use notifyAll unless you can prove every waiter waits for the same condition and that waking one is enough. Two conditions on one monitor (not-empty and not-full) need notifyAll or you deadlock a waiter of the other kind.
You reach for wait/notify when you are implementing a simple condition on a private lock and you want to stay on intrinsic monitors. You reach for Condition on a ReentrantLock when you need multiple conditions or interruptible waits with a clearer API. You reach for BlockingQueue, CountDownLatch, or CompletableFuture when those already model the coordination.
The cost of notify on the wrong condition is a lost wakeup: everyone sleeps forever. The cost of waiting without holding the monitor is IllegalMonitorStateException. The cost of a huge synchronized around slow work is blocking notify. Wait, do the work if you can, notify, exit the lock.
wait(timeout) returns when notified or when the time elapses; you still loop and check the condition and the clock.
Code Examples
public class Box {
private final Object lock = new Object();
private String value;
public void put(String v) {
synchronized (lock) {
while (value != null) {
waitQuiet(lock);
}
value = v;
lock.notifyAll();
}
}
public String take() {
synchronized (lock) {
while (value == null) {
waitQuiet(lock);
}
String out = value;
value = null;
lock.notifyAll();
return out;
}
}
private static void waitQuiet(Object lock) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Box box = new Box();
Thread t = new Thread(() -> box.put("ok"));
t.start();
System.out.println(box.take()); // prints: ok
t.join();
}
}Common Gotchas
`wait` without owning the monitor throws `IllegalMonitorStateException`
synchronize on the same object you wait on.
Always `while (condition) wait()`
`if` misses spurious wakes and stolen signals.
Prefer `notifyAll` when two predicates share a lock
`notify` can wake the wrong waiter.
`wait` releases the monitor
other threads can enter. That is the feature.