Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

Why wait, notify and notifyAll is defined in Object Class and not on Thread class in Java?

Why wait, notify and notifyAll is declared in Object Class instead of Thread is a famous core java interview question which is asked during all levels of Java interview ranging from 2 years, 4years to quite senior level position on java development. The beauty of this question is that it reflects what does interviewee knows about the wait notify mechanism, how does it sees the whole wait and notify feature, and whether his understanding is not shallow on this topic. Like Why Multiple inheritances is not supported in Java or why String is final in java there could be multiple answers of why wait and notify is defined in Object class and everyone could justify their reason.  

Why Wait notify method is declared in Object Class and not in Thread in JavaIn my all interview experience I found that wait and notify still remains most confusing for most Java programmers specially up-to 2 to 3 years and if they asked to write code using wait and notify they often struggle. 

So if you are going for any Java interview make sure you have sound knowledge of wait and notify mechanism as well as you are comfortable writing code using wait and notify like Produce Consumer problem or implementing Blocking queue etc. 

By the way, This article is in continuation of my earlier article related to wait and notify like Why Wait and notify requires to be called from synchronized block or method and  Difference between wait, sleep and yield method in Java, if you haven’t read you may found interesting.

Reason Why Wait, Notify, and NotifyAll are in Object Class.

Here are some thoughts on why they should not be in Thread class which make sense to me :

1. Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java. And Object class is the correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized. 

Remember synchronized and wait to notify are two different areas and don’t confuse that they are the same or related. Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait and notify are communication mechanism between two thread.

2Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.

3.  In Java in order to enter a critical section of code, Threads needs lock and they wait for lock, they don't know which threads hold lock instead they just know the lock is hold by some thread and they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than a thread in Java.

These are just my thoughts on why the wait and notify method is declared in Object class rather than Thread in Java and you have different versions than me. In reality its another design decision made by Java designers like not supporting Operator overloading in Java. Anyway please post if you have any other convincing reason why wait and notify method should be in Object class and not on Thread.

@Lipido has made an insightful comment, which is worth adding here. read his comment for the full text
"Java is based on Hoare's monitors idea (http://en.wikipedia.org/wiki/Monitor_%28synchronization%29). In Java all object has a monitor. Threads waits on monitors so, to perform a wait, we need 2 parameters:
- a Thread
- a monitor (any object)

In the Java design, the thread can not be specified, it is always the current thread running the code. However, we can specify the monitor (which is the object we call wait on). This is a good design, because if we could make any other thread to wait on a desired monitor, this would lead to an "intrusion", posing difficulties on designing/programming concurrent programs. Remember that in Java all operations that are intrusive in another thread's execution are deprecated (e.g. stop())."

Some Java articles on Thread you may like


Anonymous said...

why wait and notify method in object because threads wait for lock and lock is implemented on Object level. its as simple as this.

guru said...

Recently this questions "why wait and notify method in object class" were asked to my friend and he was quite happy to answer it correctly. its mostly because of locking.

Kazi Abdullah Saikat said...

The only reason to have wait/notify/notifyAll methods on Object is to allow locking on a per-object basis.

If you think about *just* a communication mechanism between multiple threads, then it would have been enough to have special lock objects and have these methods on that instead of the general Object class.

Javin @ run Java program from command prompt said...

@Anonymous, Thanks for your comment, I respect your opinion but would have been better if you post your convincing reason on why wait and notify is declared in Object Class?

Javin @ Java Iterator Example said...

@Kazi, Definitely lock is one of the primary reason why wait and notify is defined in Object class. Point to mention thread communication mechanism was due to separate wait() from Sleep() method which is also used to put Thread on wait or pause but can not be used to communicate between Thread.

Javi said...

Instead of having a lock in every object maybe it would have been wiser to create a special class supporting it... Most of the time it's not helpuful to see the wait/wait/notify/notifyAll methods every time you use a dot over a reference. Just my two cents.

Lipido said...

Java is based on Hoare's monitors idea (http://en.wikipedia.org/wiki/Monitor_%28synchronization%29). In Java all object has a monitor. Threads waits on monitors so, to perform a wait, we need 2 parameters:
- a Thread
- a monitor (any object)

In the Java design, the thread can not be specified, it is always the current thread running the code. However, we can specify the monitor (which is the object we call wait on). This is a good design, because if we could make any other thread to wait on a desired monitor, this would lead to an "intrusion", psosing difficulties on designing/programming concurrent programs. Remember that in Java all operations that are intrusive in another thread's execution are deprecated (e.g. stop()).

In addition, I think synchronized is not different. It is very related because it is needed to complete the monitor model:

-OPERATION 1) To acquire a monitor:
- a) synchronized block: synchronized(instance){ code }
- b) synchronized method: the same as putting synchronized(this) as the first line
- b) static synchronized method: the same as putting synchronized(CurrentClass.class){...}

- OPERATION 2) To release a monitor and block: wait operation. Releases the monitor and wait for the arrival of notify. This is because we need to have the objects monitor (synchronized needed). When notify arrives, it will try to acquire the monitor again.

- OPERATION 3) To make other threads to stop waiting on monitor. notify. To explore which threads are waiting and to select one of them, we also need to have the monitor (synchronized required). One thread will be n

Javin @ java hashtable example said...

@Lipido, Thanks for your comment.you are amazingly clear on first paragraph on highlighting why wait and notify should be in Object class. I am including your first paragraph on main article for better visibility. on synchronized perspective I am not agreed yes they are not absolutely unrelated but purpose of both are different synchronized is means to acquire and release lock and ensuring atomicity, ordering and visibility while wait and notify is used for thread communication. Once again thanks for adding value.

Anuj said...

One more reason why wait and notify are in Object Class and not inside Thread class is because if there would be another thread like Process than it can reuse same wait and notify mechanism for communication. kind of inter process communication. wait and notify are abstraction of inter process communication and that's why declared in Object class.

Nomad said...

To put it in simple words
Wait , notify , notifyall methods are only required when you want your threads to access a shared resource and a shared resource could be any java object which is on the heap.So, these methods are defined on the core Object class so that each object has control of allowing Threads to wait on it's monitor. Java doesn't have any special object which is used for sharing a common resource. No such data structure is defined.So, onus is given on the Object class to be able to become shared resource providing it will helper methods like wait(),notify() and notifyAll();

Ahmad said...

your tutorial help a lot to me even now i very much aware to java.

Niraj Singh said...

Here are my two cents. The Thread-Object communication should be in a publish subscribe model rather than polling model.

In case of polling model the Thread will have the responsibility of constantly observing the Object's state and take necessary actions. This is obviously not desirable as it will have performance overhead of checking time and the again. The onus of communicating the state change should lie with the object itself. And it achieves that by help of wait/notify methods.

Unknown said...

One more reason why wait notify notifyall in Object class because the Thread class extends Object class and Thread need lock and the locks defined in Object class.

kailash said...

this is because we lock object, we wait on object and we notify availability of object

vishwa said...

As Object represent the state of a class and as per design perspective, here we wait for object to attain some state after which we can execute some specific operations on the object and take it to different state. In the life cycle of an object many a times object needs to satisfy some precondition before some operations happen on that particular object. And the primary purpose of Thread is to interact with different objects and manage a line of execution , if wait and notify provided in Thread class it means we are waiting for line of execution(not on target object ) to achieve some state so that we can perform some operation on target object.

Nitin Banarasi said...

For better understanding why wait() and notify() method belongs to Object class, I'll give you a real life example:
Suppose a gas station has a single toilet, the key for which is kept at the service desk. The toilet is a shared resource for passing motorists. To use this shared resource the prospective user must acquire a key to the lock on the toilet. The user goes to the service desk and acquires the key, opens the door, locks it from the inside and uses the facilities.

Meanwhile, if a second prospective user arrives at the gas station he finds the toilet locked and therefore unavailable to him. He goes to the service desk but the key is not there because it is in the hands of the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about waiting customers. The service desk gives thekey to the waiting customer. If more than one prospective user turns up while the toilet is locked, they must form a queue waiting for the key to the lock. Each thread has no idea who is in the toilet.

Obviously in applying this analogy to Java, a Java thread is a user and the toilet is a block of code which the thread wishes to execute. Java provides a way to lock the code for a thread which is currently executing it using the synchorinized keywokd, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. Java is NOT AS FAIR as the service station because there is no queue for waiting threads. Any one of the waiting threads may get the monitor next, regardless of the order they asked for it. The only guarantee is that all threads will get to use the monitored code sooner or later.

Finally the answer to your question: the lock could be the key object or the service desk. None of which is a Thread.

However, these are the objects that currently decide whether the toilet is locked or open. These are the objects that are in a position to notify that the bath room is open (“notify”) or ask people to wait when it is locked wait.

ADITYA said...

my view is ..
wait(), notify(), notifyAll() methods are not only related to Thread objects. These are related to all java objects.
For example: If a customer Object wants to withdraw money from his back ac. at the same time another person crediting to that ac. Here if we call wait() method on the first customer object, that he waits till the second person credits the money to his ac. Once the credit completes 2nd person will call notify() method to notify the first.

The conclusion is: We have this requirement on all java objects including Threads. Thats why these methods are available in Object class for global use.

Unknown said...

can we avoid wait() , notify() or notifyAll() while using any object ? i was asked question "Suppose my application is single threaded and I am not going to use wait() or notify() any where in application then why should i borrow that load in my application ? " does any option to avoid this load or any other importance of the method other than synchronization.

Anonymous said...

@Nitin Banarasi excellent explanation

Anonymous said...

@Nitin Banarasi seriously, apt explantion .

Chema said...

And why not Java created a special class called Monitor with these methods ?
If I would need an object for holding locks , I would create a new Monitor()

Indeed, when I create a new monitor, I usually do "Object monitor = new Monitor()"

Anonymous said...

great explanation with real time example

Anonymous said...

those methods can be put in Thread class also(Just assume, nothing to loose). In case of static synchronized method, the lock should be acquired at class level but not object level. How can you support from this aspect.

Unknown said...

had wait and notify been at thread level then lock would also have been at thread level and thread includes multiple objects which would have locked so many objects .To avoid unnecessary locking , its better to have lock on single object which is supposed to be synchronized

Anonymous said...

why wait and notify defined in object class not in thread class. If suppose that defined in thread class with lock mechanism then it will work happily or any problem for execution plz explain??.

Arun Singh said...

I wud say,
A thread may have more than one object locked. so obj.wait() clears which object's lock has to be released. So the object calls wait() method directly.

Unknown said...

Well These methods should be in object class because Thread can call these methods on any JAVA OBJECT.Thats the simple answer

Santhosh dk said...
This comment has been removed by the author.

Post a Comment