Tuesday, November 13, 2007

Understanding Object wait()

The general rule of thumb to use the wait statement is as follows. This idiom addresses the issue of both missed notifications and early notifications.

synchronized(synclock) {
while (condition_does_not_hold) {
syncLock.wait();
}
// Perform action appropriate to condition
}
// Perform action that needs to be done outside the synchronized block

When wait is called on an Object's instance ...
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

No comments: