File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Why wait() within synchronized context? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Why wait() within synchronized context?" Watch "Why wait() within synchronized context?" New topic

Why wait() within synchronized context?

Kishore Kondreddi

Joined: May 10, 2006
Posts: 3
why all the three methods�wait()/notify()/notifyAll()�must be called
from within a synchronized context?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


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 ]

[Jess in Action][AskingGoodQuestions]
Kishore Kondreddi

Joined: May 10, 2006
Posts: 3
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

Joined: Jul 15, 2003
Posts: 1078
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.
I agree. Here's the link:
subject: Why wait() within synchronized context?
jQuery in Action, 3rd edition