Search code examples
javasynchronizednotify

Calling notify() vs ending synchronized block Java


I'm new to thread programming and I have a confusion like below.Let's take the following code block.

synchronized(obj)
{
   //do operations
   //obj.notify();
   //post operations
   // last statement 
}

Now until the "last statement" executes, the monitor for obj will not be released even after calling notify(). So is it worth calling notify() here?. Because anyway when the synchronized block exits, isn't it equal to calling notify().


Solution

  • No, when you exit synchronized block neither notify() nor notifyAll() is called and all other threads that were waiting on the same lock calling wait() will not be waken up.

    Here are some cons regarding automated call to notifyAll() Automatic notify()/notifyAll() on leaving a synchronized block