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

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?

Related

Why to use wait method on strings or other objects?

I have following piece of code:
synchronized void myMethod() {
String s="aaa";
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The code throws exception ...
I have seen codes using wait method on threads which is self explainable and logical..
why would one use wait method on an object like string instead of using it on main thread?
what is its use?
are there any practical implementations like this?
Thanks in advance
Your sample code won't work because the method is synchronizing on the instance that myMethod is called on, while the wait is called on the string. It will cause an IllegalMonitorStateException. You have to call wait and notify on the same object that you're locking on. The threads that get notified are the ones waiting on the lock that notify is called on.
Locking on a string object is a bad idea, don't do it. You don't want to lock on things where you can't reason about who can acquire them because anybody could acquire them. Some other code elsewhere in the application could be locking on the same string value, and you'd have the potential for strange interactions, deadlocking because the other code was taking your lock, or have the other code notifying you. Do you want to have to think about how strings are pooled when debugging some multithreading behavior?
You can limit who can acquire your lock by defining your own lock and making it private, like this:
private final Object LOCK = new Object();
so only threads calling the methods of the object you're controlling access to can acquire the lock:
public void myMethod() {
synchronized(LOCK) {
...
}
}
That way you know exactly what can acquire the lock, it's not available to every thread in the application. The lock can be acquired by anything that can get a reference to that object, so keep the reference private.
The way your example uses wait without a loop with a condition variable is very suspect. A thread can exit from a call to wait without having been notified. Even if a thread is notified, that doesn't give it any special priority with the scheduler. Another thread can barge in and do something, possibly something affecting the state that the notification was alerting the waiting thread to, between the time the thread is notified and the time that the thread can reacquire the lock it gave up when it started waiting. For both reasons there needs to be a loop where the thread retests a condition when it wakes from waiting.
Also if by "codes using wait method on threads" you mean code where a Thread object is used as a lock, that's another thing to avoid doing, see the API documentation for Thread#join:
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.
You first need to be synchronized on the Object before calling wait. This is where you are getting the exception from.
void test() {
String s = "AAA";
synchronized( s ) {
s.wait();
}
}
The same thing must be done when you call notify, but in this case it is a very very bad idea because if a thread enters this method it will never return. Although considering it is a String literal you may be able to get away with it by using the same literal in another method in the same class, but don't count on it.
wait() method is implemented in Object, and String extends object so it can be used.
why someone use it? ask him. its not a programming question.
something i can think of:
he could be using "lock1".wait() in one class and "lock1".notify() in other, it will be something like global lock object
because literals are interned by
the compiler and thus refer to the same object
but its VERY VERY BAD PRACTICE
This is an example of synchronization with no affect.
First of all, it is unlikely you will need to synchronize on String, it is immutable after all, therefore, you don't need it to perform anything asynchronously.
Second, you are likely to be synchronizing on the incorrect object anyways, no correctly written program would use String as a synchronization lock.
Third and finally, s is a local variable. In fact, it holds exactly the same pattern that JCIP specifically tells you not to use if you inline it:
synchronized (new Object()) {
// ...
}
This is synchronization without effect, as it does not guarantee the purpose of the synchronized keyword: serialized access, lock and release semantics that require that only one thread execute the synchronized block at any given time.
Because of this, each thread will have their own lock - not good.

Does it need synchronization if a thread class has just one instance?

Referring to this topic(How to pause Thread execution), Peter Knego said:
Loop must be inside synchronized block.
But I don't see the point of synchronization if only one instance is there.
In another case, if the thread class has multiple instances and they are copping with different variables, does the loop need to be synchronized.
Actually, I wrote a few programs using threads (with multiple instances) without considering synchronization and they works fine.
You must synchronize any access to shared state. If all of your instances access local storage, then they are thread safe. If your methods are thread safe, they do not require synchronization. If you had a static (e.g. global) resource, and modified it in multiple threads then that is likely to be non-thread safe (excluding atomic operations of course).
The answer says
Use synchronized, wait() and notify() for that.
Create an atomic flag (e.g. boolean field) in the thread to be stopped. Stoppable thread monitors this flag in the loop. Loop must be inside synchronized block.
When you need to stop the thread (button click) you set this flag.
Thread sees the flag is set and calls wait() on a common object (possibly itself).
When you want to restart the thread, reset the flag and call commonObject.notify().
You cannot call wait() or notify on an object unless you get a lock on it's monitor. And putting it inside synchronized block is a way to do that.
this is because the wait and notify are part of the condition variable and using them without synchronizing on them leads in the general use-case to race conditions
the normal way of using wait is
synchronized(this){
while(someCondition())
wait();//while loop is needed to combat spurious wakeups
}
and you wake it up with
synchronized(this){
adjustCondition();
notify();
}
if you didn't synchronize on the condition as well then you get into a race for example
you just tested someCondition() and got true so you need to wait. but before you get a chance to another thread executes the adjustCondition();notify(); block
but the first thread will still enter the wait() (because the condition has already been checked) and which may lead to deadlock
The Thread monitor needs to be synchronized in your case. This is done only for the actual wait call, because it requires that. I recommend to have a special wait Object for this to not accidental synchronize on something else.
final static Object threadPauseMonitor = new Object();
// ...
while (shouldPause.get()) {
synchronized(threadPauseMonitor) {
threadPauseMonitor.wait();
}
}
Where shouldPause is an AtomicBoolean. Please note the while to counter the malicious spurious wakeup that can possibly occur.

Concept behind putting wait(),notify() methods in Object class [duplicate]

This question already has answers here:
How can the wait() and notify() methods be called on Objects that are not threads?
(10 answers)
Closed 5 years ago.
I am just having hard time to understand concept behind putting wait() in Object class. For this questions sake consider if wait() and notifyAll() are in Thread class.
class Reader extends Thread {
Calculator c;
public Reader(Calculator calc) {
c = calc;
}
public void run() {
synchronized(c) { //line 9
try {
System.out.println("Waiting for calculation...");
c.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + c.total);
}
}
public static void main(String [] args) {
Calculator calculator = new Calculator();
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
calculator.start();
}
}
class Calculator extends Thread {
int total;
public void run() {
synchronized(this) { //Line 31
for(int i=0;i<100;i++) {
total += i;
}
notifyAll();
}
}
}
My Question is that what difference it could have made? In line 9 we are acquiring lock on object c and then performing wait which satisfy the condition for wait that we need to acquire lock on the object before we use wait and so is case for notifyAll we have acquired lock on object of Calculator at line 31.
I am just having hard time to understand concept behind putting wait() in object class For this questions sake consider as if wait() and notifyAll() are in thread class
In the Java language, you wait() on a particular instance of an Object – a monitor assigned to that object to be precise. If you want to send a signal to one thread that is waiting on that specific object instance then you call notify() on that object. If you want to send a signal to all threads that are waiting on that object instance, you use notifyAll() on that object.
If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread. How would thread1 know that thread2 was waiting for access to a particular resource? If thread1 needed to call thread2.notify() it would have to somehow find out that thread2 was waiting. There would need to be some mechanism for threads to register the resources or actions that they need so others could signal them when stuff was ready or available.
In Java, the object itself is the entity that is shared between threads which allows them to communicate with each other. The threads have no specific knowledge of each other and they can run asynchronously. They run and they lock, wait, and notify on the object that they want to get access to. They have no knowledge of other threads and don't need to know their status. They don't need to know that it is thread2 which is waiting for the resource – they just notify on the resource and whomever it is that is waiting (if anyone) will be notified.
In Java, we then use objects as synchronization, mutex, and communication points between threads. We synchronize on an object to get mutex access to an important code block and to synchronize memory. We wait on an object if we are waiting for some condition to change – some resource to become available. We notify on an object if we want to awaken sleeping threads.
// locks should be final objects so the object instance we are synchronizing on,
// never changes
private final Object lock = new Object();
...
// ensure that the thread has a mutex lock on some key code
synchronized (lock) {
...
// i need to wait for other threads to finish with some resource
// this releases the lock and waits on the associated monitor
lock.wait();
...
// i need to signal another thread that some state has changed and they can
// awake and continue to run
lock.notify();
}
There can be any number of lock objects in your program – each locking a particular resource or code segment. You might have 100 lock objects and only 4 threads. As the threads run the various parts of the program, they get exclusive access to one of the lock objects. Again, they don't have to know the running status of the other threads.
This allows you to scale up or down the number of threads running in your software as much as you want. You find that the 4 threads is blocking too much on outside resources, then you can increase the number. Pushing your battered server too hard then reduce the number of running threads. The lock objects ensure mutex and communication between the threads independent of how many threads are running.
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 the key 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 synchronized keyword, 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 bathroom is open (“notify”) or ask people to wait when it is locked wait.
The other answers to this question all miss the key point that in Java, there is one mutex associated with every object. (I'm assuming you know what a mutex or "lock" is.) This is not the case in most programming languages which have the concept of "locks". For example, in Ruby, you have to explicitly create as many Mutex objects as you need.
I think I know why the creators of Java made this choice (although, in my opinion, it was a mistake). The reason has to do with the inclusion of the synchronized keyword. I believe that the creators of Java (naively) thought that by including synchronized methods in the language, it would become easy for people to write correct multithreaded code -- just encapsulate all your shared state in objects, declare the methods that access that state as synchronized, and you're done! But it didn't work out that way...
Anyways, since any class can have synchronized methods, there needs to be one mutex for each object, which the synchronized methods can lock and unlock.
wait and notify both rely on mutexes. Maybe you already understand why this is the case... if not I can add more explanation, but for now, let's just say that both methods need to work on a mutex. Each Java object has a mutex, so it makes sense that wait and notify can be called on any Java object. Which means that they need to be declared as methods of Object.
Another option would have been to put static methods on Thread or something, which would take any Object as an argument. That would have been much less confusing to new Java programmers. But they didn't do it that way. It's much too late to change any of these decisions; too bad!
In simple terms, the reasons are as follows.
Object has monitors.
Multiple threads can access one Object. Only one thread can hold object monitor at a time for synchronized methods/blocks.
wait(), notify() and notifyAll() method being in Object class allows all the threads created on that object to communicate with other
Locking ( using synchronized or Lock API) and Communication (wait() and notify()) are two different concepts.
If Thread class contains wait(), notify() and notifyAll() methods, then it will create below problems:
Thread communication problem
Synchronization on object won’t be possible. If each thread will have monitor, we won’t have any way of achieving synchronization
Inconsistency in state of object
Refer to this article for more details.
Answer to your first question is As every object in java has only one lock(monitor) andwait(),notify(),notifyAll() are used for monitor sharing thats why they are part of Object class rather than Threadclass.
wait and notify operations work on implicit lock, and implicit lock is something that make inter thread communication possible. And all objects have got their own copy of implicit object. so keeping wait and notify where implicit lock lives is a good decision.
Alternatively wait and notify could have lived in Thread class as well. than instead of wait() we may have to call Thread.getCurrentThread().wait(), same with notify.
For wait and notify operations there are two required parameters, one is thread who will be waiting or notifying other is implicit lock of the object . both are these could be available in Object as well as thread class as well. wait() method in Thread class would have done the same as it is doing in Object class, transition current thread to waiting state wait on the lock it had last acquired.
So yes i think wait and notify could have been there in Thread class as well but its more like a design decision to keep it in object class.
wait - wait method tells the current thread to give up monitor and go to sleep.
notify - Wakes up a single thread that is waiting on this object's monitor.
So you see wait() and notify() methods work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait() method and through notify method (or notifyAll) threads which are waiting on the object's monitor are notified that threads can wake up.
Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class.
To reiterate threads wait on an Object's monitor (lock) and notify() is also called on an object to wake up a thread waiting on the Object's monitor.
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 detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html
This is just my 2 cents on this question...not sure if this holds true in its entirety.
Each Object has a monitor and waitset --> set of threads (this is probably more at OS level). This means the monitor and the waitset can be seen as private members of an object. Having wait() and notify() methods in Thread class would mean giving public access to the waitset or using get-set methods to modify the waitset. You wouldnt want to do that because thats bad designing.
Now given that the Object knows the thread/s waiting for its monitor, it should be the job of the Object to go and awaken those threads waiting for it rather than an Object of thread class going and awakening each one of them (which would be possible only if the thread class object is given access to the waitset). However, it is not the job of a particular thread to go and awaken each of the waiting threads. (This is exactly what would happened if all these methods were inside the Thread class). Its job is just to release the lock and move ahead with its own task. A thread works independently and does not need to know whihc other threads are waiting for the objects monitor (it is an unnecessary detail for the thread class object). If it started awakening each thread on its own.. it is moving from away its core functionality and that is to carry out its own task. When you think about a scene where there might 1000's of threads.. you can assume how much of a performance impact it can create. Hence, given that Object Class knows who is waiting on it, it can carry out the job awakening the waiting threads and the thread which sent notify() can carry out with its further processing.
To give an analogy (perhaps not the right one but cant think of anything else). When we have a power outage, we call a customer representative of that company because she knows the right people to contact to fix it. You as a consumer are not allowed to know who are the engineers behind it and even if you know, you cannot possibly call each one of them and tell them of your troubles (that is not ur duty. Your duty is to inform them about the outage and the CR's job is to go and notify(awaken) the right engineers for it).
Let me know if this sounds right... (I do have the ability to confuse sometimes with my words).
the wait() method will release the lock on the specified object and waits when it can retrieve the lock.
the notify(), notifyAll() will check if there are threads waiting to get the lock of an object and if possible will give it to them.
The reason why the locks are a part of the objects is because the resources (RAM) are defined by Object and not Thread.
The easiest method to understand this is that Threads can share Objects (in the example is calculator shared by all threads), but objects can not share Attributes ( like primitives, even references itself to Objects are not shared, they just point to the same location). So in orde to make sure only one thread will modify a object, the synchronized locking system is used
Wait and notify method always called on object so whether it may be Thread object or simple object (which does not extends Thread class)
Given Example will clear your all the doubts.
I have called wait and notify on class ObjB and that is the Thread class so we can say that wait and notify are called on any object.
public class ThreadA {
public static void main(String[] args){
ObjB b = new ObjB();
Threadc c = new Threadc(b);
ThreadD d = new ThreadD(b);
d.setPriority(5);
c.setPriority(1);
d.start();
c.start();
}
}
class ObjB {
int total;
int count(){
for(int i=0; i<100 ; i++){
total += i;
}
return total;
}}
class Threadc extends Thread{
ObjB b;
Threadc(ObjB objB){
b= objB;
}
int total;
#Override
public void run(){
System.out.print("Thread C run method");
synchronized(b){
total = b.count();
System.out.print("Thread C notified called ");
b.notify();
}
}
}
class ThreadD extends Thread{
ObjB b;
ThreadD(ObjB objB){
b= objB;
}
int total;
#Override
public void run(){
System.out.print("Thread D run method");
synchronized(b){
System.out.println("Waiting for b to complete...");
try {
b.wait();
System.out.print("Thread C B value is" + b.total);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Do I need extra synchronization when using a BlockingQueue?

I have a simple bean #Entity Message.java that has some normal properties. The life-cycle of that object is as follows
Instantiation of Message happens on Thread A, which is then enqueued into a blockingQueue
Another thread from a pool obtains that object and do some stuff with it and changes the state of Message, after that, the object enters again into the blockingQueue. This step is repeated until a condition makes it stop. Each time the object gets read/write is potentially from a different thread, but with the guarantee that only one thread at a time will be reading/writing to it.
Given that circumstances, do I need to synchronize the getters/setters ? Perhaps make the properties volatile ? or can I just leave without synchronization ?
Thanks and hope I could clarify what I am having here.
No, you do not need to synchronize access to the object properties, or even use volatile on the member variables.
All actions performed by a thread before it queues an object on a BlockingQueue "happen-before" the object is dequeued. That means that any changes made by the first thread are visible to the second. This is common behavior for concurrent collections. See the last paragraph of the BlockingQueue class documentation:
Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.
As long as the first thread doesn't make any modifications after queueing the object, it will be safe.
You don't need to do synchronization yourself, because the queue does it for you already.
Visibility is also guaranteed.
If you're sure that only one thread at a time will access your object, then you don't need synchronisation.
However, you can ensure that by using the synchronized keyword: each time you want to access this object and be sure that no other thread is using the same instance, wrap you code in a synchronized block:
Message myMessage = // ...
synchronized (myMessage) {
// You're the only one to have access to this instance, do what you want
}
The synchronized block will acquire an implicit lock on the myMessage object. So, no other synchronized block will have access to the same instance until you leave this block.
It would sound like you could leave of the synchronized off the methods. The synchronized simply locks the object to allow only a single thread to access it. You've already handled that with the blocking queue.
Volatile would be good to use, as that would ensure that each thread has the latest version, instead of a thread local cache value.

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

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

Categories

Resources