my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes wait & notify Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply locked New topic
Author

wait & notify

Poornachandran R
Ranch Hand

Joined: Sep 11, 2002
Posts: 47
Hi,
Can anyone explain why wait() and notify() methods are defined in Object rather than Thread ?
Poorna
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443
Originally posted by Poornachandran R:
Hi,
Can anyone explain why wait() and notify() methods are defined in Object rather than Thread ?
Poorna

Because, I guess, objects(or classes) owns the monitor so they should be the only one that can release the lock.
But I also think that it is more intuitive if they put it in the Thread class like this:
Thread.wait(Object o)
Anyway, only the thread that holds the lock can execute these 2 methods.
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
I am trying to understand this same question myself. This is as far as I have gotten...
Can anyone explain why wait() and notify() methods are defined in Object rather than Thread ?

Answer 1. Every object has a wait set. When an object is created, its wait set is empty. When a thread invokes the wait() method on an object, the thread is added to the object�s wait set. When another thread invokes the notify() method on an object, a thread is removed from the object�s wait set.
When a thread invokes notify(), the JVM does not select just any waiting thread to unblock. Instead, the JVM selects a thread from one object�s wait set. When a thread invokes notifyAll(), the JVM does not unblock all waiting threads. Instead, the JVM unblocks all threads in one object�s wait set.
The wait set is manipulated only by methods wait, notify, notifyAll and Thread.interrupt.
Answer 2. Entities possessing both locks and wait sets are generally called monitors. An Object can serve as a monitor.
I think the answer to your question is knowing what a monitor is. I do not know much about monitors, but I have some good references:
(1) Programming Language Pragmatics, Michael L. Scott, Chapter 12 Concurrency Here
(2) Foundations of Multithreaded, Parallel, and Distributed Programming, Gregory Andrews, Chapter 5 Monitors Here
[ July 17, 2003: Message edited by: Marlene Miller ]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Please don't post the same question in multiple forums. Now we've got multiple conversations going on about the same thing, unaware of other comments. Followups can go here or here please. Thanks.
[ July 17, 2003: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: wait & notify