• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why wait() within synchronized context?

 
Kishore Kondreddi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why all the three methods�wait()/notify()/notifyAll()�must be called
from within a synchronized context?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

An object's "monitor" is a sort of abstract entity associated with an object and used for commnunicating with other threads. It's basically a hidden instance variable of an object, like a Collection. When a thread calls wait(), it adds itself to the Object's monitor "collection", goes to sleep and waits for a signal from that monitor to wake it up. When a thread calls notify() or notifyAll(), it sends a signal to that monitor -- or more to the point, to one or more threads that have called wait() on that same monitor.

I expect that you understand that any time that multiple threads need to share data, synchronization (locking) is involved. Given that I've explained how wait() and notify() involve adding and removing things from a collection from multiple threads, it should be obvious why wait() and notify() must be called with the object's monitor locked.
[ May 11, 2006: Message edited by: Ernest Friedman-Hill ]
 
Kishore Kondreddi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Hill,

because each thread is accessing shared monitor , before accessing this shared monitor it has to get lock of that object. correct?

but i thought lock and monitor are same, is it not?
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think what Ernest is getting at is that adding/removing threads from the wait set (the collection he refers to) needs to be synchronized. If more than one thread were allowed to do it concurrently there would be problems, but I don't really know since the methods are native and I'm not sure what issues there might be concerning the implementation.

The "monitor" and "lock" are for all intents and purposes the same thing, yes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic