Java Thread wait() => blocked? - java

According to Java thread state info calling wait() will result a thread to go in BLOCKED state. However this piece of code will result (after being called) in a Thread in WAITING State.
class bThread extends Thread {
public synchronized void run() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Have I got something wrong? Can anybody explain this behaviour to me?
Any help would be appreciated!

The thread is WAITING until it is notified. Then it becomes BLOCKED trying to reenter the synchronized region until all other threads have left.
Relevant parts from the link you posted (about WAITING):
For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object.
and (about BLOCKED):
A thread in the blocked state is waiting for a monitor lock to [...] reenter a synchronized block/method after calling Object.wait.
The last part occurs when the thread tries to return from wait(), but not until then.

The monitor executes one thread at a time. Assuming you have T1-T10 threads, 9 are BLOCKED and one is RUNNABLE. Every once in a while, the monitor picks a new thread to run. When that happens, the chosen/current thread, say T1, goes from RUNNABLE to BLOCKED. Then another thread, say, T2, goes from BLOCKED to RUNNABLE, becoming the current thread.
When one of the threads needs some information to be made available by another thread, you use wait(). In that case, the thread will be flagged as WAITING until it is notify()ed. So, a thread that is waiting will not be executed by the monitor until then. An example would be, wait until there are boxes to be unloaded. The guy loading boxes will notify me when that happens.
In other words, both BLOCKED and WAITING are status of inactive threads, but a WAITING thread cannot be RUNNABLE without going to BLOCKED first. WAITING threads "don't want" to become active, whereas BLOCKED threads "want" to, but can't, because it isn't their turn.
I think.

Where did you see it say stuff like that?
In the same page you linked, thread.state, it clearly states that
WAITING will be after Object.wait()
BLOCKED will be before entering synchronized

Waiting is when it's not doing anything at all. Blocked is when it's trying to start running again but hasn't been allowed to yet.

There is some confusing terminology going on here.
When a thread calls wait on an object it goes into the WAIT state.
When threads are waiting to grab a lock, they belong to the wait set for that lock, but they are in the BLOCKED state.
Confusing but somehow it makes sense!

Just as a reminder, you should always call wait() inside a while loop waiting on the condition for entering the synchronized region/critical section. This is because Java has "spurious wakeups" (essentially, a thread can wakeup at any moment for no reason).

Related

Why do we need notify() for inter thread communication

From the JAVA docs for Object notify()
The awakened thread will not be able to proceed until the current
thread relinquishes the lock on this object.
This means that unless the Thread which notifes, its synchronized block is complete and it releases the lock, the waiting thread cannot proceed. If that's the case then whats the point of having notify() if the sync block is going to be executed anyway? What's the actual use of notify() if it doesn't wake up the waiting thread and let it do its job?
Good question. Will point you to take a look at the Thread State Class.
A thread that calls the Object.notify method enables a thread that previously called Object.wait is now enabled to be scheduled by the thread scheduler. In parlance, the thread that was waiting is now "runnable". Although it is "runnable", it is not "running".
It can only continue running when the thread invoking notify releases the lock - one way is when it exits out of the synchronized block.
There are a lot of schematics on the web on the Thread States. Some of them are completely incorrect or confusing since they introduce terminology not in the official docs. Here is one that makes sense to me.
Strictly speaking, we don't: we could have the waiting thread run a loop where it re-acquires the lock, checks the condition, and sleeps for a short amount of time. But using wait() and notify() is much more efficient, because then the waiting thread doesn't keep waking up and tying up CPU (and tying up the lock).
notify() and notifyAll() are used to wake up thread(s) that called wait() on the same object on which notify() or notifyAll() is called.
Without call to notify() those "waiting" threads will wait forever (although JVM spec says that threads may sometime wake up without call to notify).
Also because call to notify() doesn't releases the lock associated with the object itself that call usually is the last statement in a synchronized block.
So notify() is used together with wait() and not by itself.
Usually the use case is like the following (blocking queue with limited size).
Method that adds element to queue (some pseudo code)
synchronized(lockObject) {
if (size < LIMIT) {
addElement();
lockObject.notifyAll(); //notifying threads that are waiting to get element from empty queue
} else {
lockObject.wait(); // waiting for other thread to get element from queue and make room for new element
}
}
Method that gets element
synchronized(lockObject) {
if (size > 0) {
getElement();
lockObject.notifyAll(); // notify threads that there is a room for new element
} else {
lockObject.wait(); // waiting for other thread to put element into the queue
}
}
Also calling lockObject.wait() releases lock on lockObject. More details regarding that could be found here: Java : Does wait() release lock from synchronized block
Notifying is what wakes up a thread that is waiting. If you remove the notify then waiting threads stay waiting (barring spurious wakeups but let’s not go there for now).
(Interrupting wakes up the thread but the guidance is to use it for cancellation only. Interruption targets a specific thread, where notifying lets the scheduler decide which threads are affected.)
When a thread calls wait it has to have the lock, then the wait method lets go of the lock.
When a thread calls notify it has to have the lock.
As a practical matter the notify can’t take effect on any waiting thread until the notifying thread relinquishes the lock. The first thing the notified thread is going to need to do anyway is to try to acquire the lock. All the passage you're quoting is trying to say is that the wakeup doesn't occur instantaneously when a thread calls notify.
So what happens here is that the notifying thread lets go of the lock and sends the notify to the scheduler, the scheduler decides which thread to notify, then the notified thread wakes up and contends for the lock in order to leave the wait method.
Imagine if you need a thread to wait for another thread to do something that it may or may not even currently be actively working on. For example, a thread that's waiting for a job to do may need to wait until another thread has put a job on the list of jobs it should do if that list is empty. How would you do this?
You can't just use some form of mutual exclusion. There may be long periods of time when there's no work to do and not thread holds any lock on the queue. There may just not be any work to do right now. The thread that does work needs to wait, without holding any lock, until another thread has given it some work to do.
So somewhere, there's a thread that does something like this:
Acquire the lock that protects some shared state that another thread might be waiting for a change to. (In this case, the job queue.)
Change the shared state to reflect the fact that the thing a thread might need to wait for has happened. (That is, put a job on the queue.)
Release the lock and let any waiting thread(s) know that the thing has happened.
So what could our code to wait look like? Perhaps:
Acquire the lock that protects the shared state.
Check whether we need to wait or not. (Is there a job on the queue?)
If we need to wait, wait. (If not, wait for a job to be placed on the queue.)
...
Oops, we have a problem. The thing we're waiting for can't happen because we hold the lock. No other thread can change the shared state. (Our thread to put a job on the queue can't touch the queue until we release the lock we acquired in step 1.)
Let's try it again:
Acquire the lock that protects the shared state.
Check whether we need to wait or not. (Is there a job on the queue?)
If we don't need to wait, exit this algorithm. (If there's a job, take it off the queue, release the lock, and do it.)
Release the lock. (So another thread can put a job on the queue.)
Wait for the thing to happen.
...
Oops, we have another problem. What if the thing we're waiting for happens after step 4 but before step 5. Since the lock has been released, the thing we're waiting for can happen. We can't check again because we don't hold the lock. How can we ensure we don't wait for something that has already happened, which may mean waiting forever?
To solve this, we need an atomic "unlock and wait" operation. That's what wait does. And we also need some operation that can end this wait that can be called by the thread that changed the shared state so that we no longer need to wait. That's what notify does.

Can two threads waiting on the same monitor be called a deadlock?

Two threads are waiting on the same monitor, for example if one thread calls wait on 'lock' and the other thread that acquired the monitor also calls wait before notifying the first thread. Now both the threads are waiting but no one gets notified. What would I call this situation? Can this be called a deadlock?
Edit:
Assumption is that these are the only two threads and there is no way for them to be notified from elsewhere.
Update: I just created the situation I described in question. The following piece of code works okay most of the time when changer thread is started before the listener thread. However when I start listener before changer, the program just hangs after printing two lines (one from changer and one from listener thread). Would the situation where I call listener before changer be called a deadlock?
package demo;
public class ProducerConsumer {
public static int SAMPLE_INT = 0;
public static void main(String[] args) {
PC pc = new PC();
Thread changer = new Thread(new Runnable() {
public void run(){
try {
pc.producer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread listener = new Thread(new Runnable(){
public void run() {
try {
pc.consumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
changer.start();
listener.start();
}
}
class PC {
Object lock = new Object();
public void producer() throws InterruptedException {
synchronized(this){
for (int i=0; i<5; i++){
ProducerConsumer.SAMPLE_INT++;
System.out.println("Changed value of int to: " + ProducerConsumer.SAMPLE_INT);
wait();
notify();
}
}
}
public void consumer() throws InterruptedException{
synchronized(this){
for (int i=0; i<5; i++){
System.out.println("Receieved Change: " + ProducerConsumer.SAMPLE_INT);
notify();
wait();
}
}
}
}
Output when changer is started before listener:
Changed value of int to: 1
Receieved Change: 1
Changed value of int to: 2
Receieved Change: 2
Changed value of int to: 3
Receieved Change: 3
Changed value of int to: 4
Receieved Change: 4
Changed value of int to: 5
Receieved Change: 5
Program terminates.
Output when listener is started before changer:
Receieved Change: 0
Changed value of int to: 1
Program doesn't terminate.
Thanks.
If these are the only two threads involved (eg with access to the monitor) then yes. If there are additional threads which can access the monitor and unlock it then no.
Keep in mind however that you are talking about two topics - a monitor is generally a mutex in threading terms. But wait is something associated with a condition variable which while requiring a mutex to work, performs a more subtle task of deliberately blocking on a thread based on a condition which one thread signals to another with a caveat known as spurious wakeups.
This is not a deadlock because there is a way out of this situation - if a third thread invokes notify() or notifyAll() then the previous two waiting threads would return back to ready state.
Deadlock usually cannot be resolved within the application itself and requires restart.
That is why I would not call your situation a deadlock.
There are two other terms that describe thread coordination problems:
Livelock and Starvation
Here are the exact definitions of LoveLock and Starvation - Starvation and LiveLock
This is not a LiveLock either, because the threads do not act in responce to each other.
Your situation is probably closest to the term Starvation, but not exactly starvation. Starvation is when a thread waits for resource that have been taken for a very long time. In your case the resource is the lock of the object and it will never be acquired again. So your best shot is something like "An Endless Starvation".
I personally would call this a "producer-consumer bug" because the wait-notify mechanism describes and manages coordination of threads for the "producer-consumer" pattern and this approach (wait without a notify) is just a developer bug or missuse of the methods.
A deadlock basically means that a thread is holding a lock (first lock) and then wants to acquire another lock (second lock) which it can never acquire because the second lock is held by another thread which wants to acquire the first lock. This could also happen in a chain of threads, for example, where Thread1 has LockA, Thread2 has LockB, Thread3 has LockC and they are waiting for the locks held by other threads (for example, Thread1 wants LockB, Thread2 wants LockC, and Thread3 for LockA). In this case, none of the threads can ever proceed.
Only these kind of scenarios are called deadlocks; a thread holding a lock waits for another lock which will never be acquired unless it releases its lock.
This calling wait on the lock object technically releases the lock the thread was holding.
So, to answer your question, I don't think you can call the scenario you mentioned in the question as deadlock.
For this scenario, better use wait(timeout) method rather than wait().
Even if there is no notify from the other thread, it will release the lock after timeout period
#S.Doe With the edit of your question, the situation is the deadlock because there are 2 threads and both are in wait queue and not executing any code on it.
There is no 3rd thread also which means that no thread is in runnable/running state even. Its a deadlock.
You cannot control with this code which thread will acquire lock first. If consumer acquires first, its call to notify() is not waking up any thread and it goes to wait leaving the lock. Now Producer acquires lock, produces and goes to wait.
This is a general race condition problem and you need to control which thread should start execution first (Producer in this scenario)
You can use CyclicBarrier to control the sequence of thread call.
I think both Krasimir and Andy have given right answers. I wanted to give an additional proof (sort of) that this situation is technically not a deadlock.
And that comes from the fact that the Java thread dump on this program does not report that this is a deadlock. Although it is possible that Java thread dump misreports, we can assume that if there is a deadlock, the thread dump does a pretty good job of reporting it.
So, I ran your program with the listener (consumer) started before the changer (producer) in the program's textual order, and like you, I received a hang. At this point, I got a thread dump (there are various ways to do it, looking at your IDE is the easiest). Relevant portions of the thread dump are here [1].
If this were a deadlock, the thread dump would clearly say so (something like Found one Java level deadlock). But since it does not, we can rest assured that this is not a deadlock.
Looking at the thread dump (which is a 'stack' dump of each thread) is still very instructive. You can see that both the producer and consumer threads have first locked the lock <0x000000076abca250> (entered the monitor) as suggested by the lock ... line. And curiously (or not), both of them are waiting on the same lock (as suggested by the waiting on ...) line!
This is where the subtlety of entering the thread's wait set comes into picture. In order for a thread to wait on a lock, it must first give up that same lock.
This is exactly what consumer#wait does (the second thread in the dump below): gives up the exclusive lock so some other thread can actually catch hold of it and hopefully wake him up via a notify.
Alright, the consumer is now taken out of contention for that lock. Note that the notify call already done by consumer before wait may or may not go astray. If it does, then we have this hanging situation that we are trying to reason.
In the meanwhile, the producer thread has also started running (perhaps a little later). Since the consumer has 'given up' the lock in order to wait on it, producer grabs the lock and it too now executes wait. Like consumer, now it is waiting on the same lock in the same hope that someone would come along and wake him up!
Again, technically, none of the two threads has exclusively locked any lock. Since both the threads are waiting, they have given up the lock and should some other thread come along (too bad, not in this case!), their hope might go to fruition. But in this case, the program is going to hang forever since nothing else does anything to change the situation (the JVM hanging has its reasons in threads being non-daemon, but that is another detail). Thus, wait-notify are the low-level primitives in Java that are used for thread communication and their appropriate use is via the so-called condition variable. It's like threads acknowledging that they are working on a shared resource and they communicate with each other any boundary cases (e.g. a shared queue being empty of full) via these primitives.
If a thread actually holds a lock L1 (i.e. it is executing within the synchronized section) and suddenly, it requires to grab another lock L2 to carry out its task and at the same time, another thread while hold L2, is looking to grab L1, then deadlock occurs. Since that is not a situation here, this is not a deadlock.
Having said that, I have a number of suggestions to make to improve this code. Like Joshua Bloch says, "Example code must be exemplary":
Remove the line Object lock = new Object(); from the PC class. It serves no purpose. You are NOT locking on it. You are locking on a monitor associated with the instance of PC: PC pc = new PC();.
Consider renaming SAMPLE_INT to something like count in public static int SAMPLE_INT = 0; and make it volatile. It's not guaranteed that the changes made to this variable are visible to another thread.
There is no need to define SAMPLE_INT in ProducerConsumer, define it in PC.
Like someone suggested, consider using a CountdownLatch while starting threads.
[1] Thread dump (I used the tmp package name):
2016-02-23 15:02:49
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.74-b02 mixed mode):
"DestroyJavaVM" #13 prio=5 os_prio=31 tid=0x00007f80b381c800 nid=0x1303 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Thread-0" #11 prio=5 os_prio=31 tid=0x00007f80b480b000 nid=0x5903 in Object.wait() [0x00000001294e5000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076abca250> (a tmp.PC)
at java.lang.Object.wait(Object.java:502)
at tmp.PC.producer(ProducerConsumer.java:44)
- locked <0x000000076abca250> (a tmp.PC)
at tmp.ProducerConsumer$1.run(ProducerConsumer.java:14)
at java.lang.Thread.run(Thread.java:745)
"Thread-1" #12 prio=5 os_prio=31 tid=0x00007f80b6801000 nid=0x5703 in Object.wait() [0x00000001293e2000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076abca250> (a tmp.PC)
at java.lang.Object.wait(Object.java:502)
at tmp.PC.consumer(ProducerConsumer.java:55)
- locked <0x000000076abca250> (a tmp.PC)
at tmp.ProducerConsumer$2.run(ProducerConsumer.java:24)
at java.lang.Thread.run(Thread.java:745)

Confusion on Wait ,Notify and Sleep

I have a simple program which I am finding very confusing. The code snippet is as follows:
class Processor{
public void produce() Throws InterruptedException{
synchronized(this){
System.out.println("Producer Running...");
wait();
System.out.println("Resumed");
}
}
public void consume() Throws InterruptedException{
synchronized(this){
Thread.Sleep(2000);
System.out.println("Consumer Running... Press return key to return");
scan.nextLine();
notify();
Thread.sleep(5000);
}
}
Now my question is that , when we call wait() in the "produce" method the execution is immediately transferred to the "consume" method. (produce and consume are executed in separate threads). But when the notify(); is called in the "consume " method ,the execution does not immediately transfer. It waits for Thread.sleep(5000) to complete . why is this so ?
Well, the reason is quite simple.
When a thread calls wait() on certain object it goes into a waiting state and it stops executing (it is removed from scheduling). When waiting a thread releases all the monitors it has taken (and it needs to regain them after waking up)
When a thread calls notify() on certain object it wakes up another thread waiting over it, but it does not go into a waiting state itself, so it keeps running.
After your producer thread calls notify it keeps running and performing a five seconds sleep. While sleeping a thread retains all monitors that it has taken (you are inside a synchronized(this) block hence you have a monitor for "this" object). Scheduler cannot run the consumer thread that was just notified since it needs to readquire the monitor before resuming, and it wont be freed until your producer thread stops sleeping and gets out of the synchronized block
Although you seem to be missing some code needed for me to explain completely accurately, I'll do my best to provide an explanation that would be applicable even if my guess was incorrect.
wait() and notify() are methods called on a mutex object -- in this case, this.
wait() causes the currently executing thread to pause and give up that mutex (I think it's just the mutex that wait() is called on, could be all of them. Not sure), after which another thread can acquire the mutex and start executing. This is why you observe an immediate transfer of control when wait() is executed.
When notify() is called on a mutex, a thread waiting on that mutex wakes up and attempts to acquire the lock. However, it cannot do so until the lock is available -- in this case, until the lock (this) is released by the thread that calls notify() (the consumer thread). The mutex is only released once the consumer thread exits from the synchronized block, which is after the Thread.sleep(5000); call in your code. sleep() does not release any mutexes that the current thread has acquired, so the first thread has to wait until the second has finished sleeping and exited the synchronized block.
That is why wait() transfers control immediately, while notify() (in this case) has the currently executing thread finish its method before the formerly waiting thread can continue execution.
Assuming that you are calling both methods using the same object from difference threads.
If you want to don't wait 5000 miliseconds, use wait(5000) instead of Thread.sleep(5000).
The notify method, take one (random) previously waiting thread, that is waiting to acquire the lock (of an object) that the running/current thread has taken before, and mark it to resume as soon the current thread release the lock.
In your this case, it will release the lock and soon the Thread.sleep(5000) finish and leave the synchronized block.
Be aware, if you call produces or consume with diferents objects things will go totally diferent. I strongly suggest to read this article.
Hope it helps! As the good answers below!
The reason is that Thread.sleep(5000L) does not release the lock on the object's monitor while it's waiting, contrary to wait(5000L). This is specified in the Javadoc for Thread.sleep() :
... The thread does not lose ownership of any monitors.
Whereas the javadoc for Object.wait() specifies:
... This method causes the current thread (call it T) to place itself
in the wait set for this object and then to relinquish any and all
synchronization claims on this object...

Object wait() and notify() revisited

Though there are lots of articles and SO posts on this topic , still i have some doubts. So please help me understand. Say i write :
1.Class A(){}
2.public static void main(String[] s){
3. A obj= new A();
4. synchronized(obj){
5. while(!condition)
6. obj.wait();
7. }
8.}
Now according to explanations ,if we don't use synchronized block, Thread woken-up from sleep may loose notifications. BUT line 6 released the lock on obj i.e. its monitor is owned by another thread.
Now when that thread invoked notify() , how does this thread get notified since obj's monitor is not owned by this thread. Moreover , line 4 code executes only once ,NOT on each wake-up event of this thread. So what EXACTLY is NEED of synchronized before wait()?
Edit: "line 4 code executes only once" wrong assumption. Threads in synchronized blocks reacquire lock after they are resumed from sleep as mentioned in answer.Thanks
It works as explained in the javadoc for Object#wait, emphasis mine:
The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
so once the waiting thread is notified, it reacquires the monitor before proceeding to the next instruction (in your case: while(!condition)).
"So what EXACTLY is NEED of synchronized before wait()?" : Condition is shared across the thread and any change in condition should be thread safe and that is reason for having synchronized. Here condition is not some random condition but this is something for which your thread is going wait for.
Hope this helps.

How exactly does Java wait() method work?

Consider that thread 1 is running following code:
while (true) {
synchronized (this) {
wait();
...Do Something ...
}
}
And lets say we have thread 2 that notifies thread 1, ie:
synchronized (thread1)
thread1.notify();
}
My question is lets say thread 1 got woken up, and is doing something (so its running currently). Then lets say thread2 does notify on thread1 while thread1 is running.
Will thread1 run again when it finishes "do something"? Or will it just sleep instead?
Is my question clear enough?
Thank you.
Say thread 1 got woken up, and is doing something (so its running currently). Then lets say thread2 does notify on thread1 while thread1 is running. Will thread1 run again when it finishes "do something"? Or will it just sleep instead?
The latter. Primitive notify events are delivered to threads that are waiting at the time of the notify / notifyAll call. If no threads are waiting, the notify does nothing: the events are discarded.
Then is it possible to get wait queued? I would like to notify threads when new event happens, but will not like to have threads busy waiting... Is this possible?
Primitive notify events are not and cannot be queued.
If you need notifications to be queued, you will need to use a higher level concurrency class rather than wait / notify. For example Semaphore may do the job ... without busy waiting. Other possibilities are CyclicBarrier and CountdownLatch.
wait() works by purely halting the operation of a thread until another thread notifies it that it can continue running. A synchronized method is one that can only be run by one thread at a time.
A thread won't be 'notified' when it already running.
If a thread is running, and another thread notifies it, then the notify is "wasted" -- it has no effect. If the first thread calls wait() again, it will be returned into the wait pool as normal.

Categories

Resources