I'd advise using the Monitor pattern (http://en.wikipedia.org/wiki/Monitor_(synchronization)) anyway, that could save you from errors later on, especially as your use case gets more complex:
class Monitor
{
/** Initialised to `false` by default in Java. */
boolean condition;
synchronized void waitForSomething()
{
while(!condition)
{
wait();
}
}
synchronized void signal()
{
condition = true;
notify();
}
}
That way everything is nicely encapsulated and protected (I don't usually use private
modifiers in examples, but you might want to enforce additional "privacy" in your code, specifically making the condition
private
.)
As you can observe, in my condition loop there is wait()
call, as opposed to your example where you have notify()
in the loop instead. In most use cases doing what you did with notify
is a mistake, although I can't speak for your particular case as you didn't provide us with enough details. I am willing to bet yours is the typical one though, for which the Monitor pattern applies beautifully.
The usage scenario is along the following: thread that wants to wait for something calls waitForSomething
and another thread may cause it to continue by invoking signal
method which will set the condition flag.