The other day I was going through Kathy sierra/Bert bates book on SCJP and came across the code which is given as an example of wait/notify/notifyAll(chapter 9, code with classes - Reader and Calculator.). But the weird thing is that even if I remove the call to notify/notifyAll, the waiting threads come out of wait stage. Is this a case of spurious wake-up? I tried it on both windows and Linux machines but the results are more or less same.
Below is a revised version of the code that you posted. It launches all the
MyReader threads and then starts one Calculator. Calculator then counts
to 100, sets ready=true, notifies the listeners and pauses to let a waiting
thread run. It then counts again, once for each MyReader thread. If you
take out the yield() statement, you can see the calculator rush ahead.
Some notify() calls may get lost and MyReader threads will be left waiting. Notice how changing the 'ready' value is synchronized together with the
wait() and notify() calls. Also, the idiom of "while(condition==false) wait();"
should always be used. (I'm quoting from the Sun documentation.) Reset
of the condition variable after the wait() is important too.