top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

Why and how wait ,notify and notifyAll methods called in Object class not in Thread class?

+1 vote
2,255 views
Why and how wait ,notify and notifyAll methods called in Object class not in Thread class?
posted Oct 9, 2013 by Nagarajuk

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+2 votes

Each and every class in java have a super class i.e. Object.
Since each object of any class in java has a lock, which is acquire by a thread to use that particular.
Once a thread get a lock of any object to use it, it does. And after completion, it is the job of the object to inform other thread which are waiting for that object that hey my lock is free now and you can get me by calling its notify() or notifyAll() to release waiting threads.
In short if i say, Lock is required by a thread to use it and wait(), notify() and notifyAll() inform these threads about its lock availability and unavailability.

answer Oct 9, 2013 by Nikhil Omar
+1 vote

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 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 notify are two different area and don’t confuse that they are 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.

2 )Locks 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 critical section of code, Threads needs lock and they wait for lock, they don't know which threads holds 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 thread in Java.

answer Oct 9, 2013 by anonymous
0 votes

You can use wait() and notify() to synchronise your logic. As an example

synchronize(lock) {
lock.wait(); // Will block until lock.notify() is called on another thread.
}

// Somewhere else...
...
synchronize(lock) {
lock.notify(); // Will wake up lock.wait()
}

with lock being the class member Object lock = new Object();

answer Oct 10, 2013 by Satyabrata Mahapatra
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...