What is the difference between the notify() and notifyAll() methods in Java?
sobes.tech AI
Answer from AI
The difference is that notify() "wakes up" only one, randomly chosen thread from the set of threads waiting on the object's monitor, whereas notifyAll() "wakes up" all threads waiting on that monitor.
-
notify(): Used when you are sure that only one of the waiting threads can perform useful work after receiving the notification. This can be more efficient, as it avoids unnecessary wake-ups and context switches for other threads. -
notifyAll(): Used when you are not sure which thread should receive the notification, or when multiple threads can benefit from the notification. For example, when working with resource pools or in producer-consumer models, where multiple consumers may be ready to process a new item.
After being notified, threads compete to re-acquire the monitor. Only the thread that successfully acquires the monitor can continue execution. The other notified threads will go back to waiting until they can acquire the monitor.
class SharedResource {
private boolean conditionMet = false;
public synchronized void waitForCondition() throws InterruptedException {
while (!conditionMet) { // Using a while loop instead of if, to protect against "spurious" wake-ups
wait(); // The thread releases the monitor and enters waiting state
}
// Condition met, thread can continue
}
public synchronized void fulfillCondition() {
conditionMet = true;
// notify(); // Wakes up one random thread
notifyAll(); // Wakes up all waiting threads
}
}