Quiz: wait(), notify() and notifyAll() in Java: Inter-Thread Communication
Study the lesson first: wait(), notify() and notifyAll() in Java: Inter-Thread Communication
Total: 7 questions
1. What do the wait(), notify() and notifyAll() methods do in Java?
What do the wait(), notify() and notifyAll() methods do in Java?
wait(), notify() and notifyAll() are final methods of the Object class used for inter-thread communication: 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. The thread wakes up onnotify()/notifyAll(), oninterrupt()(withInterruptedException), when the timeout ofwait(ms)expires, or spuriously. Before returning fromwait(), it reacquires the monitor.notify()wakes up one arbitrary waiting thread - the JVM decides which. If nobody is waiting, the signal is lost.notifyAll()wakes up all threads waiting on this object; they get the monitor one at a time.
The methods are declared in Object, not in Thread, because a thread waits for a change in an object's state, and every object has a monitor and a wait set.
2. When do wait() and notify() throw IllegalMonitorStateException?
When do wait() and notify() throw IllegalMonitorStateException?
When the current thread doesn't own the monitor of the object whose method is called. This happens in two cases:
- the call is made outside
synchronizedaltogether, for examplelock.notify()in a regular method; synchronizedis on one object, whilewait()/notify()is called on another. A common variant: the method is declaredsynchronized(monitor ofthis), but inside it callsqueue.wait()on a field.
The compiler doesn't catch these mistakes; the exception appears only at runtime. Modern JDKs put "current thread is not owner" in the message; in Java 8 getMessage() returns null.
The monitor is required so that checking the condition and going to wait are one atomic operation: otherwise notify() could fire between the check and the call to wait(), and the thread would sleep forever.
3. Why is wait() called in a while loop and not in an if?
Why is wait() called in a while loop and not in an if?
Returning from wait() doesn't guarantee that the condition is true. There are two reasons:
- spurious wakeup: a thread can wake up without
notify(), an interrupt or a timeout - this is documented explicitly inObject.wait(); - a "stolen" condition: the thread was woken up correctly, but while it was waiting for the monitor in
BLOCKED, another thread grabbed the monitor first and changed the data. For example, with two consumers the second one takes the number, and the first one, afterif, returns it a second time.
That's why the JavaDoc recommends a single idiom:
synchronized (obj) {
while (!condition) {
obj.wait();
}
// the action that requires the condition
}
With while, the thread rechecks the condition and, if it's false, goes back to waiting. The same rule applies to await() on a Condition.
4. How do you implement producer-consumer with wait() and notify()?
How do you implement producer-consumer with wait() and notify()?
You need a shared queue object, a field holding the condition and synchronized methods. In the lesson, MyQueue holds one number and the valueSet flag:
put()waits inwhile (valueSet) wait();, stores the number, setsvalueSet = trueand callsnotify();get()waits inwhile (!valueSet) wait();, takes the number, resets the flag and callsnotify().
The condition lives in a field, not in the signal: notify() is not remembered, and if it fires before wait(), the waiting thread still sees the flag and doesn't wait at all.
The InterruptedException from wait() is not swallowed with printStackTrace(): the methods declare throws InterruptedException, and run() restores the flag with Thread.currentThread().interrupt() and ends the loop. With one producer and one consumer, the output strictly alternates: "Sent: 0", "Received: 0" and so on.
5. notify() vs notifyAll(): which one should you use?
notify() vs notifyAll(): which one should you use?
notify() is safe only when all waiting threads wait for the same condition and any of them can proceed. If threads with different conditions wait on one object (producers wait for space, consumers wait for data), notify() may wake up the "wrong" one.
Example: MyQueue with notify(), two producers and one consumer. A producer puts a number and wakes up the second producer instead of the consumer; both see the slot is taken and go into wait(). All three threads are in WAITING, nobody is left to wake them - the program just stands still without an exception. This is not a deadlock: nobody holds a monitor. The fix is notifyAll(): everyone wakes up, the extra threads recheck the condition in while and go back to sleep.
The price of notifyAll() is extra wakeups. If they matter, use a ReentrantLock with several Condition objects and wake only the right group with signal().
6. How does wait(long timeout) work?
How does wait(long timeout) work?
wait(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 why the thread woke up - notify(), timeout or a spurious wakeup. So the condition and the remaining time are checked in a loop:
long deadline = System.currentTimeMillis() + timeoutMillis;
while (!valueSet) {
long left = deadline - System.currentTimeMillis();
if (left <= 0) {
throw new TimeoutException();
}
wait(left); // wait only for the time that is left
}
wait(0) doesn't mean "don't wait", it means "wait with no time limit"; a negative timeout throws IllegalArgumentException. Just as after notify(), after the timeout the thread continues only when it reacquires the monitor.
7. What should you use instead of wait() and notify() in modern Java code?
What should you use instead of wait() and notify() in modern Java code?
For producer-consumer - a BlockingQueue from java.util.concurrent, for example new ArrayBlockingQueue<Integer>(1): put() waits for free space, take() waits for data, and the loop, the flag and the notifications are hidden inside. If you need your own waiting logic - a ReentrantLock and its Condition: several conditions on one lock (notFull, notEmpty) and signal() only for those waiting for the right one. The while rule around await() still applies.
One more argument is virtual threads. In Java 21-23, a virtual thread that calls wait() inside synchronized is pinned to its carrier thread for the entire wait, so BlockingQueue or Condition is the better choice for queues there. In Java 24 (JEP 491), a thread in Object.wait() unmounts from its carrier, and there is no need to rewrite the code for virtual threads.
You still need to know wait()/notify(): plenty of existing code is built on them, they come up in interviews, and Condition follows the same pattern.