Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

wait, notify to be called from synchronized??  RSS feed

 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi frnds,
I know that wait() method releases all the locks it has and wait for some call(notify or notifyAll), to make it move ahead. But my question is that unlike depricated methods suspend and resume, why java wants me to put both the wait() and notify() in synchronized methods(or blocks)?
Thanks in advance
Sandeep Jindal
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wait() doesn't release all locks; it only releases the lock of the object upon which it is called. Therefore, calling it without actually owning the lock on an object doesn't make sense. If you're in a block or method that synchronizes on an object, then you own the lock on that object, of course; hence the requirement. Note that the actually executing method doesn't have to be the synchronized code -- the current thread has to have entered a synchronized block on that object somewhere on the call stack.
Similarly, notify() signals that lock on an object, so once again, you've got to have ownership of the lock before you can send a message through it.
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why java wants me to put both the wait() and notify() in synchronized methods(or blocks)?

Guess #1:
When a thread invokes wait(), the thread is added to the wait set of the object on which wait() was invoked and the lock of the object is released.
If the thread did not hold the lock of the object when the thread invokes wait(), there would be a race hazard. Another thread could invoke notify() before the first thread is suspended. The notification would have no affect on the thread, effectively getting lost.
----
Guess #2:
Typically, a thread tests a condition before invoking wait.

If the thread did not hold the lock, another thread could change the condition after the first thread tested the condition but before the thread is suspended. The thread would wait forever, even though the condition has changed.
[ December 06, 2003: Message edited by: Marlene Miller ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!