Reputation: 1452
I know the mechanism of wait()
and notify()
of thread, but I am unable to understand that why wait()
and notify()
methods should be in synchronized
block? Is this mandatory?
Thanks in Advance!
Upvotes: 2
Views: 709
Reputation: 24801
Is synchronized mandatory while invoking wait/notify: Yes
Why?: Consider that synchronizing was not required. That means that a thread A could call notify() exactly at the same time while the other thread B is calling wait()(on the same object). Suppose thread B has executed part of wait() method and is context-switched to serve thread A. So the internal data-structures of wait could be in corrupt state now. Now the notify() method essentially works on the same data-structures, which now is in invalid state. Hence the entire wait/notify could go for a toss. Synchronizing guarantees that no other method could call wait/notify if there is a call to one of them already on.
Upvotes: 4