Why are wait() and notify() declared in Java's Object class? - java

Why are the wait() and notify() methods declared in the Object class, rather than the Thread class?

Because, you wait on a given Object (or specifically, its monitor) to use this functionality.
I think you may be mistaken on how these methods work. They're not simply at a Thread-granularity level, i.e. it is not a case of just calling wait() and being woken up by the next call to notify(). Rather, you always call wait() on a specific object, and will only be woken by calls to notify on that object.
This is good because otherwise concurrency primitives just wouldn't scale; it would be equivalent to having global namespaces, since any calls to notify() anywhere in your program would have the potential to mess up any concurrent code as they would wake up any threads blocking on a wait() call. Hence the reason that you call them on a specific object; it gives a context for the wait-notify pair to operate on, so when you call myBlockingObject.notify(), on a private object, you can be sure that you'll only wake up threads that called wait methods in your class. Some Spring thread that might be waiting on another object will not be woken up by this call, and vice versa.
Edit: Or to address it from another perspective - I expect from your question you thought you would get a handle to the waiting thread and call notify() on that Thread to wake it up. The reason it's not done this way, is that you would have to do a lot of housekeeping yourself. The thread going to wait would have to publish a reference to itself somewhere that other threads could see it; this would have to be properly synchronized to enforce consistency and visibility. And when you want to wake up a thread you'd have to get hold of this reference, awaken it, and remove it from wherever you read it from. There's a lot more manual scaffolding involved, and a lot more chance of going wrong with it (especially in a concurrent environment) compared to just calling myObj.wait() in the sleeping thread and then myObj.notify() in the waker thread.

The most simple and obvious reason is that any Object (not just a thread)
can be the monitor for a thread. The wait and notify are called on the
monitor. The running thread checks with the monitor. So the wait and notify methods are in Object and not Thread

Because only one thread at a time can own an object's monitor and this monitor is what the threads are waiting on or notifying. If you read the javadoc for Object.notify() and Object.wait() it's described in detail.

The mechanism of synchronization involves a concept - monitor of an object. When wait() is called, the monitor is requested and further execution is suspended until monitor is acquired or InterruptedException occurs. When notify() is called, the monitor is released.
Let's take a scenario if wait() and notify() were placed in Thread class instead of Object class. At one point in the code, currentThread.wait() is called and then an object anObject is accessed.
//.........
currentThread.wait();
anObject.setValue(1);
//.........
When currentThread.wait() is called, monitor of currentThread is requested and no further execution is made until either the monitor is acquired or InterruptedException occurs. Now while in waiting state, if a method foo() of another object anotherObject residing in currentThread is called from another thread, it is stuck even though the called method foo() does not access anObject. If the first wait() method was called on anObject, instead of the thread itself, other method calls (not accessing anObject) on objects residing in the same thread would not get stuck.
Thus calling wait() and notify() methods on Object class(or its subclasses) provides greater concurrency and that's why these methods are in Object class, not in Thread class.

A few of the other answers use the word "monitor", but none explain what it means.
The name "monitor" was coined way back in the 1970s, and it referred to an object that had its own intrinsic lock, and associated wait/notify mechanism. https://en.wikipedia.org/wiki/Monitor_%28synchronization%29
Twenty years later, there was a brief moment in time when desktop, multi-processor computers were new, and it was fashionable to think that the right way to design software for them would be to create object-oriented programs in which every object was a monitor.
Turns out not to have been such a useful idea, but that brief moment happens to be exactly when the Java programming language was invented.

Read here for an explanation of wait and notify.
It would be better to avoid these however in your applications and use the newer java.util.concurrent package.

I will put it in a simple way:
To call wait() or notify() you need to own the object monitor - this means wait() or notify() needs to be present in the synchronized block
synchronized(monitorObj){
monitorObj.wait() or even notify
}
Thats the reason these methods are present in object class

This is because,these methods are for inter thread communication and interthreadcommunication happens by using locks, but locks are associated with objects.hence it is in object class.

Wait and Notify methods are used communication between two Threads in Java. So Object class is correct place to make them available for every object in Java.
Another reason is Locks are made available on per Object basis. 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

Related

What does it mean by waiting on object monitor [duplicate]

Someone at work just asked for the reasoning behind having to wrap a wait inside a synchronized.
Honestly I can't see the reasoning. I understand what the javadocs say--that the thread needs to be the owner of the object's monitor, but why? What problems does it prevent? (And if it's actually necessary, why can't the wait method get the monitor itself?)
I'm looking for a fairly in-depth why or maybe a reference to an article. I couldn't find one in a quick google.
Oh, also, how does thread.sleep compare?
edit: Great set of answers--I really wish I could select more than one because they all helped me understand what was going on.
Lots of good answers here already. But just want to mention here that the other MUST DO when using wait() is to do it in a loop dependent on the condition you are waiting for in case you are seeing spurious wakeups, which in my experience do happen.
To wait for some other thread to change a condition to true and notify:
synchronized(o) {
while(! checkCondition()) {
o.wait();
}
}
Of course, these days, I'd recommend just using the new Condition object as it is clearer and has more features (like allowing multiple conditions per lock, being able to check wait queue length, more flexible schedule/interrupt, etc).
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
lock.lock();
try {
while (! checkCondition()) {
condition.await();
}
} finally {
lock.unlock();
}
}
If the object does not own the object monitor when it calls Object.wait(), it will not be able to access the object to setup a notify listener until the the monitor is released. Instead, it will be treated as a thread attempting to access a method on a synchronized object.
Or to put it another way, there is no difference between:
public void doStuffOnThisObject()
and the following method:
public void wait()
Both methods will be blocked until the object monitor is released. This is a feature in Java to prevent the state of an object from being updated by more than one thread. It simply has unintended consequences on the wait() method.
Presumably, the wait() method is not synchronized because that could create situations where the Thread has multiple locks on the object. (See Java Language Specifications/Locking for more info on this.) Multiple locks are a problem because the wait() method will only undo one lock. If the method were synchronized, it would guarantee that only the method's lock would be undone while still leaving a potential outer lock undone. This would create a deadlock condition in the code.
To answer your question on Thread.sleep(), Thread.sleep() does not guarantee that whatever condition you are waiting on has been met. Using Object.wait() and Object.notify() allows a programmer to manually implement blocking. The threads will unblock once a notify is sent that a condition has been met. e.g. A read from disk has finished and data can be processed by the thread. Thread.sleep() would require the programmer to poll if the condition has been met, then fall back to sleep if it has not.
It needs to own the monitor, since the purpose of the wait() is to release the monitor and let other threads obtain the monitor to do processing of their own. The purpose of these methods (wait/notify) is to coordinate access to synchronized code blocks between two threads that require each other to perform some functionality. It is not simply a matter of making sure access to a data structure is threadsafe, but to coordinate events between multiple threads.
A classic example would be a producer/consumer case where one thread pushes data to a queue, and another thread consumes the data. The consuming thread would always require the monitor to access the queue, but would release the monitor once the queue is empty. The producer thread would then only get access to write to the thread when the consumer is no longer processing. It would notify the consumer thread once it has pushed more data into the queue, so it can regain the monitor and access the queue again.
Wait gives up the monitor, so you must have it to give it up. Notify must have the monitor as well.
The main reason why you want to do this is to ensure that you have the monitor when you come back from wait() -- typically, you are using the wait/notify protocol to protect some shared resource and you want it to be safe to touch it when wait returns. The same with notify -- usually you are changing something and then calling notify() -- you want to have the monitor, make changes, and call notify().
If you made a function like this:
public void synchWait() {
syncronized { wait(); }
}
You would not have the monitor when wait returned -- you could get it, but you might not get it next.
Here's my understanding on why the restriction is actually a requirement. I'm basing this on a C++ monitor implementation I made a while back by combining a mutex and a condition variable.
In a mutex+condition_variable=monitor system, the wait call sets the condition variable into a wait state and releases the mutex. The condition variable is shared state, so it needs to be locked to avoid race conditions between threads that want to wait and threads that want to notify. Instead of introducing yet another mutex to lock its state, the existing mutex is used. In Java, the mutex is correctly locked when the about-to-wait thread owns the monitor.
Mostly wait is done if there is a condition say a queue is empty.
If(queue is empty)
queue.wait();
Let us assume the queue is empty.
In case if the current thread pre-empts after checking the queue, then if another
thread adds few elements to queue, the current thread will not know and will go for wait
state. Thats wrong.
So we should have something like
Synchornized(queue)
{
if(queue is empty)
queue.wait();
}
Now let us consider what if they made wait itself as synchronized. As already mentioned in one of the comments, it releases only one lock. That means if wait() was synchronized in the above code only one lock would have been released. Implies that current thread will go for wait with the lock for the queue.

Why it is not possible to build binary semaphore with if statement inside in Java

I have a small question that makes me a little confused.
This is my code:
public synchronized void P() {
while(!_state) {
this.wait();
}
_state = false;
}
This method is responsible for taking semaphore.
Why it is not possible to build binary semaphore with if statement instead of while loop?
The oracle docs says:
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is
done with the object.
So exactly only one thread should be inside the P() method -> so only one thread should be blocked on wait() method. Rest of threads should be blocked on P() method level. But when I am replacing while() for if() it does not work properly
Why it is not possible to build binary semaphore with if statement instead of while loop?
For a deep answer, you should work through Oracle's Guarded Blocks tutorial.
The shorter answer is, there's a couple of reasons why _state could be false when the wait() call returns:
Multiple consumers: It generally is safer to wake sleepers with notifyAll() instead of notify(), and if you write a program in which two or more threads could call the P() function, you probably only want one of them to be allowed to proceed when some other thread calls the V() function. So, if they all "wake up", you'll want just one to set _state=false; and you'll want the others to go back to sleep.
The same object is getting notifyAll() calls for more than one reason. It's not good practice, but it happens, especially in projects where many developers contribute to the code. In that case, you don't wan the P() call to return if the object was notified for the wrong reason. You want it to go back and continue waiting.
The documentation for o.wait() says that it is allowed to return even when object o has not been notified at all. This is known as "spurious wakeup." It happens rarely, and only in some operating systems, but they allow it because it enables a more efficient implementation of wait() and notify().
synchronized method is equivalent to synchronized(this) block.
Only 1 thread is allowed to enter synchronized block. By entering it, thread aquires lock. When you wait inside sync block, you release the lock (object monitor) and park current thread. At this moment, another thread is allowed to enter that block. Execution will continue when other thread will invoke notify or notifyAll on the same object that wait was invoked. Notified thread will "exit wait state" when given sync block's lock will be released.
To sum up - wait does not work like you expect, it does not block execution, only puts waiting thread to sleep, allowing other threads to aquire sync lock.
So you cannot do what you want to achieve, because wait works differently then you expect. What you want to use here, is ReentrantLock. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html

Does Thread.join() release the lock? Or continue to hold it?

As I understand it, internally obj.join() calls wait(). This means that join() always releases the lock (because wait() always releases the lock after being called).
The API doc explains:
This implementation uses a loop of this.wait calls conditioned on
this.isAlive. As a thread terminates the this.notifyAll method is
invoked. It is recommended that applications not use wait, notify, or
notifyAll on Thread instances.
People here on SO say that join() does not release any lock because the API does not mention it explicitly. But this logic seems strange to me.
Here is the main logic from join()'s code:
while (isAlive()) {
wait(0);
}
This site further adds to the confusion (I think they are mistaken):
3) The third difference between the wait() and join() methods is that when a thread calls the wait() method it releases any lock held for the object on which wait() is called, but calling the join() method doesn't release any monitor or lock.
wait releases the monitor held on the object which wait is invoked on, but not any other monitors.
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits [...].
In other words, given the following:
synchronized (a) {
synchronized (b) {
b.wait();
}
}
At b.wait(), the current thread releases b's monitor, but not a's monitor.
If t.join() is implemented using t.wait() internally, then t's monitor is released while waiting, but not any other monitor.
This join implementation is a case of leaky abstraction, by the way. If Thread used a private final Object monitor; to wait on instead, we could say that join released no monitors, even if it used wait internally without us knowing. There would be no reason to document the implementation detail of using wait, because the monitor would be inaccessible to us, so we would not need to know about it.
The reason that we know join uses wait internally is that the people who originally wrote the method chose a monitor which is accessible to us. This created the need to reveal the implementation details. join is not really supposed to release monitors from our perspective, just wait for a thread to complete, but an implementation was chosen which required us to know more about it than we should.
Though the excellent answer from #Radiodef clarifies & elaborates the leaky abstraction shortcoming, in simpler terms to answer #vrinchvucz confusion the answer is,
Yes, when a thread invokes t.join it does acquire and release 'a' monitor lock. That monitor lock is that of the thread t itself since the implementation of join method on Thread class implemented it by using this.wait inside of the synchronized join method which is the leaky abstraction issue that #Radiodef points to.
Thus unless the thread acquires the monitor lock of t itself before it invokes t.join we can say that NO client/user acquired monitor locks are released in the t.join invocation (because the monitor lock in question is NOT any that the client/user code acquired in the thread that invoked t.join).
This since as clearly stated in the docs for Object#wait
Note that the wait method, as it places the current thread into the
wait set for this object, unlocks only this object; any other objects
on which the current thread may be synchronized remain locked while
the thread waits.
Which is why the docs for Thread#join does not mention anything about locks being released while still giving the implementation details regarding the use of this.wait.

Java Thread Synchronized object for wait and notify

When we are using wait and notify in thread environment. I have a class to process data as background process. And when there is no data to process it should call wait.
synchronized(some_object){
wait();
}
In another class I am adding the data again. I need call notify() method.
synchronized(some_object){
runnabale_object.notify();
}
Why i should use same object for synchronized block in those two different class. As i read synchronize is used to
The "Synchronized" keywords prevents concurrent access to a block of
code or object by multiple Threads.
But these two are different block. But i can understand the problem when we use multiple threads. While one thread block other can call notify before the same thread call notify.
My Questions
Can we use different lock objects (synchronized(object)) for single threaded environment?
Best way of use same lock object when we have wait and notify in different classes?
Can we use different lock objects (synchronized(object)) for single threaded environment?
In a single threaded environment, you don't need the locks. You can use anything you want or nothing at all.
In a single threaded environment you can guarantee no thread is wait()ing so the notify() will not do anything.
Best way of use same lock object when we have wait and notify in different classes?
When you notify(), you must perform a state change. When you wait() in a loop you much check for that state change. If you don't do this you can have two problem.
the notify() is lost
the wait() wakes spuriously, ie no notify.
when there is no data to process it should call wait.
Not when, but while.
Wait and notify are low-level primitive operations that are meant to be used in a very specific way.
In a consumer thread:
synchronized(lock) {
while (thereIsNothingToProcess()) {
lock.wait();
}
processSomething();
}
In a producer thread:
synchronized(lock) {
makeSomethingAvailableToProcess();
lock.notifyAll(); //or lock.notify() if you think you can get away with it.
}
If you follow this exact pattern, then:
You will not run into trouble when multiple consumers are competing for the same thing-to-be-processed,
You will not run into trouble because of spurious wakeups, and
You will not run into trouble because of the lost notification problem.
I've had the same question so I looked it up. The reason that two synchronized block can be used in the same object, is that 'wait()' will actually release the monitor so that other thread can obtain the guardian of the same object.

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

i know that wait() method always written in synchronized method/block and make lock on Object but i want to only know that what problem is arise at that time when this all methods are in Thread class ?
They are also in the Thread class. But a thread instance here is equally well suited as a synchronization object as any other object.
In addition, there have already been voices that question this decision of sun, since now every object carries the burden to be able to be synchronized on, and IMHO they should have refactored this out to separate objects long ago.
If I need to have something to synchronize on, I often do:
private Object syncObject = new Object();
Then I can do my
synchronized(syncObject)
everywhere in the code and do not have to bother with anyone else accidentially synchronizing on this.
The problem with using them on a Thread object is that the Thread uses this lock for it own purposes. This is likely to lead to confusion and odd bugs.
These method's context is a lock associated with every object in Java so we can't move them to the Thread class. For example we might do something like this. Thread 1 adds an item to a list and notifies other threads about it. Thread 2 waits for a list update and does something with it:
thread 1
synchronized (lock) {
list.add(item);
lock.notifyAll();
}
thred 2
synchronized (lock) {
list.wait();
... do something with list
}
If these methods were moved to a thread, the thing we done here would be impossible.
These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.
The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.
For more explanation read: Why wait() ,notify() and notifyAll() methods are in Object class instead of Thread class?

Categories

Resources