Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object Class

 
Kuppuraj Govindhasamy
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are wait(), notify() and notifyall() methods defined in the Object class?
 
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!

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.
 
Henry Wong
author
Marshal
Pie
Posts: 21122
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Henry
[ February 23, 2007: Message edited by: Henry Wong ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic