• Post Reply Bookmark Topic Watch Topic
  • New Topic

wait/notify and synchorized

 
Pradeep bhatt
Ranch Hand
Posts: 8933
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is required that wait/notify be put inside an synchronized block.
 
Jason Cox
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Pradeep Bhat:
Why is required that wait/notify be put inside an synchronized block.

Java synchronization uses object and class level "monitors". These monitors are like locks that protect certain critical areas of code. The wait() and notify() methods use these monitors. The synchronized keyword indicates to java that a class will use monitors.
Here's a link to a JavaWorld article that explains this better:
http://www.javaworld.com/javaworld/jw-07-1997/jw-07-hood.html
Good Luck!
Jason
 
Max Habibi
town drunk
( and author)
Sheriff
Posts: 4118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Pradeep Bhat:
Why is required that wait/notify be put inside an synchronized block.


Basically, when a thread waits, it's letting others use it's object. Correspondingly, when a thread cals notify, it releases the object. Now, neither of these would make much sense if the thread didn't actually own the object, would they? The thread would be taking liberties with stuff that didn't belong to it. When a thread synchronizes on an object, it 'own' it: thus, it can give it away.
M
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is required that wait/notify be put inside a synchronized block.

Because of the way wait sets interact with locks.
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.
The lock is released and the thread is suspended atomically. Otherwise, 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.
The key to understanding Java wait and notify is to understand Hoare monitors and Brinch Hansen critical regions.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!