arun8 arun8 - 1 month ago 12
Java Question

Is it okay to call notify() on a lock object before calling wait() on it?

I am using wait() and notify() in my code and there is a scenario where the execution can reach notify() first before a wait is actually called on the lock object on another thread. I created a flag "isWaitCalled" in the lock object and using it to skip notify() call if wait() is not called already. Is this flag "isWaitCalled" redundant? Is it okay if notify() is called before wait in one of the scenarios?
Thread A:

synchronized (syncObject) {
try {
if (!syncObject.isLoadComplete) {
syncObject.isWaitCalled = true;
syncObject.wait();
}
} catch (Exception ex) {
}
}


ThreadB:

synchronized (syncObject) {
try {
if (!syncObject.isLoadComplete) {
syncObject.isLoadComplete =true;
if (syncObject.isWaitCalled) {
syncObject.notify();
}
}
} catch (Exception ex) {
}
}

Answer

There is no special problem with invoking notify() or notifyAll() on an object on which no thread is waiting. In particular, it will not block, and in this sense the isWaitCalled variable serves no purpose.

Be aware, however, that notifications have effect only on threads that are already waiting when the notification is delivered. In particular, a thread that invokes the object's wait() method after the notify() will block until the next notify. For this reason, the standard wait / notify paradigm requires threads to check before waiting whether they need to wait at all.

In its simplest form, threads would check the value of some shared variable to determine whether to wait and whether, after returning from from waiting, to resume waiting. The notifying thread, for its part, is then responsible for modifying that variable appropriately before sending its notification. That's more or less the reverse of what you present.