Why wait, notify and notifyAll are defined in Object Class?

Why wait, notify and notifyAll is defined in Object Class?

Why wait, notify and notifyAll are not defined in Thread Class?

Above questions are very popular in interview. Interviewer will often ask this question to test the knowledge of wait(), notify() and notifyAll() methods in Java multithreading. This is very important question because it also clears the concept of a Thread and Lock. Now lets see why wait(), notify() and notifyAll(), these methods are in Object class and not in Thread Class.

Reasons why wait, notify and notifyAll are defined in Object Class

In java there is a concept of Monitor (What is monitor in java?) , each object has a monitor. So when a thread perform a wait operation, the operation involves two things a Thread and a Monitor. When a thread which currently owns a monitor object can suspend itself inside the monitor with the help of Wait method what it do is it releases the monitor object and enters in a wait state. The wait state ends when another thread call notify method inside the monitor object. So wait and notify methods happens on any object which threads are accessing to. So this is a main reason to have wait, notify and notifyAll is defined in Object Class.

Also the wait and notify are communication mechanisms used by the objects to communicate between two thread.
Why wait, notify and notifyAll  are defined in Object class
Also Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.
Also as these wait(), notify() and notifyAll() methods are defined in the Object class all objects in java can able to use it.

We will see what these methods do ?

wait()
Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

notify()
Wakes up a single thread that is waiting on this object’s monitor

notifyAll()
Wakes up all threads that are waiting on this object’s monitor.

Thus we have seen why wait(), notify() and notifyAll() methods are defined in the Object Class and not in Thread class.

About the author pranav

has written 205 post in this blog.

Pranav is a Java Developer and his liking is into the computer networking, windows , linux and latest tech updates. Started this blog focusing on java, windows, linux and internet tutorials and tips.

         
        

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>