Java Thread Communication: Implementation of wait(), notify() and notifyAll()
This article explains how Java's wait(), notify() and notifyAll() methods work for inter‑thread communication, covering the required synchronized context, lock release behavior, wake‑up conditions, the importance of using while loops to avoid spurious wake‑ups, and provides a concise code example.
In Java, the java.lang.Object#wait() method causes the current thread to pause execution and enter the waiting queue until it is awakened by another thread invoking notify() or notifyAll() , or until it is interrupted.
Before calling wait() , the thread must hold the monitor lock of the target object, which means the call must occur inside a synchronized method or synchronized block.
When wait() is executed, the thread releases the monitor lock, leaves the running state, and moves to the waiting queue (note that Thread.sleep(long) does not release the lock). After being notified, the thread must reacquire the monitor lock before it can continue execution.
The overloaded wait(long timeout) version additionally specifies a maximum waiting time; if the timeout expires, the thread is automatically awakened.
It is essential to use a while loop to re‑check the condition after waking up, in order to guard against spurious wake‑ups.
Example code:
synchronized(lockObject) {
while (!condition) {
lockObject.wait();
}
// take the action here;
}The notify() and notifyAll() methods must also be called from within a synchronized context, i.e., when the calling thread holds the monitor lock.
After invoking notify() or notifyAll() , the current thread does not immediately release the lock; the lock is released only after the synchronized block or method finishes, allowing waiting threads to compete for the lock.
In practice, developers usually prefer notifyAll() to avoid missed notifications.
Summary : Understanding the wait‑notify mechanism, the lock release behavior, and the need for proper condition checks is a common interview topic for Java concurrency.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.