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 Object Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Object Class" Watch "Object Class" New topic

Object Class

Kuppuraj Govindhasamy

Joined: Feb 23, 2007
Posts: 4
Why are wait(), notify() and notifyall() methods defined in the Object class?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


Welcome to JavaRanch!

Once you understand what these methods do, it's easy to understand why they're in Object. "wait()" means "wait for a message to be sent to me through this object," while "notify" and "notifyAll" mean, respectively, "send a message to one thread through this object" and "send a message to all threads waiting on this object." The wait/notify mechanism treats each object as a sort of message board, through which threads can communicate. That's why the methods are in Object.

[Jess in Action][AskingGoodQuestions]
Henry Wong

Joined: Sep 28, 2004
Posts: 20525

Originally posted by Kuppuraj Govindhasamy:
Why are wait(), notify() and notifyall() methods defined in the Object class?

Well, I guess the short answer is ... because it was designed that way.

Now, IMHO, I am not sure that this was a good design decision. If you look at other threading systems (Solaris, POSIX, Windows, etc.), a lock (mutex, monitor, etc.) and condition variable are separate entities. You declare a mutex to lock with, and you declare a condition variable to attach to the mutex to use for notifications.

In Java, any object can be used as a synchronization lock, and the condition variable support is also be part of the object. This makes it's usage very convenient as you don't have to declare a mutex or cond var, you simply use a common data object that needs to be protected, as the lock and notification variable.

For condition variable support, I would have preferred a separate class, that implements the wait(), notify(), and notifyAll(). (Of course, you would also need a method to set the object that this condvar would use as it's synchronization lock.) This way, you can have many condition variables share the same synchronization object.

[ February 23, 2007: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: Object Class
It's not a secret anymore!