How does wait() and notify() work in Java? - java

I am new to OS/multithreading and I'm wondering how wait() and notify() work together. I just saw this: Producer Consumer Solution in Java
And I'm kind of confused. Let's say I called wait() in PC.consume() method. When I reach the line that says notify() in PC.produce(), how does this wait in PC.consume() know that THAT is the one being notified? There could be other places that could be notified so how does it exactly know which to notify?
Thanks!

Wait and notify are called on the same object, the one being used as a lock (in the example that’s the object referenced by the local variable pc). The term used in the javadoc (here is the start of the api doc for the notify method) is “monitor”:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
The OS has a thread scheduler that is making the arbitrary decision described in the javadoc, it decides things like when threads get context-switched or who gets notified.
So when a thread in consume waits, it goes dormant. Then eventually some other thread (in the example there are only two threads that acquire the lock on pc) calls notify on the same object the first thread called wait on, the scheduler picks the thread to be notified (has to be the first thread here because nothing else is waiting), and the notified thread wakes up and checks if there is anything to consume so it can know whether to proceed.

Related

What circmustances can cause a thread to be transferred from the wait queue to the blocked queue?

Under what conditions can this happen?
As far as I know
Blocked queue is a buffer between threads producing objects and consuming objects.
Wait queue prevents threads from competing for the same lock.
So thread gets a lock, but is unable to be passed onto consumer as it is now busy?
The question makes only sense under the assumption that it actually means “What circumstances can cause a thread to change from the wait state to the blocked state?”
There might be a particular scheduler implementation maintaining these threads in a dedicated queue, having to move threads from one queue to another upon these state changes and influencing the mind set of whoever originally formulated the question, but such a question shouldn’t be loaded with assumed implementation details. As a side note, while a queue of runnable threads would make sense, I can’t imagine a real reason to put blocked or waiting threads into a (global) queue.
If this is the original intention of the question, it should not be confused with Java classes implementing queues and having similar sounding names.
A thread is in the blocked state if it tries to enter a synchronized method or code fragment while another thread owns the object monitor. From there, the thread will turn to the runnable state if the owner releases the monitor and the blocked thread succeeds in acquiring the monitor
A thread is in the waiting state if performs an explicit action that can only proceed, if another thread performs an associated action, i.e. if the thread calls wait on an object, it can only proceed when another thread calls notify on the same object. If the thread calls LockSupport.park(), another thread has to call LockSupport.unpark() with that thread as argument. When it calls join on another thread, that thread must end its execution to end the wait. The waiting state may also end due to interruption or spuriuos wakeups.
As a special case, Java considers threads to be in the timed_waiting state, if they called the methods mentioned above with a timeout or when it executes Thread.sleep. This state only differs from the waiting state in that the state might also end due to elapsed time.
When a thread calls wait on an object, it must own the object’s monitor, i.e. be inside a synchronized method or code block. The monitor is released upon this call and reacquired when returning. When it can’t be reacquired immediately, the thread will go from the waiting or timed_waiting state to the blocked state.

wait() , notify() - which thread first unlock?

Trying to understand wait() and notify(). I know when thread A went to wait() it will be waked up by notify() from other thread.
But what will happens if threads A,B,C went to wait() in represented order? Who will be waked up by notify()? According to my experiments A thread will be waked up at first. I'm right?
Does it means that system knows in which order threads went to wait() ?
From the documentation for notify(), emphasis mine:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
Some other APIs, such as Semaphore, have a concept of "fairness", where you can ensure that threads do proceed in the order in which they blocked.
Section 17.2.2 Notification of Java Language Specification:
There is no guarantee about which thread in the wait set is selected.
So, observed behavior is not guaranteed and should not be relied upon.
No, the VM does not know in which order the threads were put in Waiting state.
When you call notify(), one of them will be back to Alive/Runnable state and there is no way to know which one the VM will choose.
Sometimes they can run in the order they were put in Waiting state, but the specification does not guarantee that. So in a different VMs you can have a completely different results or even in the same VM, if you run the code multiple times.
No, there is no guarantee about the order. The javadoc of the notify method is pretty clear on this:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
There's no such an order. Either thread has an equal opportunity to get into runnable state. Actually JVM/OS can see them only as a set of waiting threads, they don't know any order.
In terms of your experiment, to get into a fair conclusion, actually you have to perform it for a huge number of times.
In threads, you can expect an order (FIFO), only if you are using something like a strong Semaphore. Then these threads are put into a waiting queue and fist comer would be first served.

How does Java's notify work?

When calling notify() in a thread in which there are multiple instances waiting, how does Java(or JVM) choose which thread to wake up?
Sources you can use for an answer:
Java Language Specification chapter 17.2.2 Notification:
There is no guarantee about which thread in the wait set is selected.
Javadoc on Object.notify() reads:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
notify method wakes up only one thread waiting on the object and that thread starts execution. So if there are multiple threads waiting for an object, this method will wake up only one of them. The choice of the thread to wake depends on the OS implementation of thread management.

thread state java

I'd like to check if my reasoning is correct.
First of all, I should provide a few details about the problem I'm trying to solve. A thread (part of a program) does the following things:
it starts
it calls Thread.sleep (20ms)
it calls getIn() method
it tries to get a lock (lock.lock())
if successfully gets the lock it calls Thread.sleep (100ms)
if the lock is not available it calls waitingCond.await()
after calling Thread.sleep (100ms) it calls lock.unlock()
it calls another method getOut()
it terminates (thread.join())
Given that, the following is my guessing about the thread state:
READY TO RUN state
TIMED WAITING state
WAITING state
WAITING state
BLOCKED state
WAITING state
WAITING state
TERMINATED state
Thanks
First of all, the state you describe with READY TO RUN is actually RUNNABLE. For my bachelor thesis I had created a transition graph showing the different thread states and when they ought to change. You haven't described the semantics of getIn(), so I guess it is just a random method.
If the thread is executing code, for instance on of your methods getIn() or getOut() it is RUNNABLE and not WAITING. BLOCKED is actually only a very short transition state, which is always entered when a thread tries to claim a lock. If the lock is not available the thread keeps being blocked and cannot execute another action as you imply in step 6. Also it cannot invoke a method after calling Thread.sleep() it has to wait, until the time is elapsed.
I would correct it the following way:
RUNNABLE
TIMED WAITING
RUNNABLE
BLOCKED
TIMED WAITING
BLOCKED
RUNNABLE
TERMINATED
Disclaimer: There is no guarantee for the transitions. It might even be, that a JVM vendor decides to implement the underlying mechanics in another way, for instance it could implementing blocking by spin-waiting.
If you want to dive deeper into this topic use a Profiler to find out the states of your thread. I have written one of my own to detect those states: Java Concurrency Profiler, but there are others out there as well, for instance VisualVM or YourKit.

java: wait(), notify() and synchronized blocks

I learned that calling an Object's wait() method will release the object monitor, if present.
But I have some questions regarding calling notify() on this object by another thread:
(when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?
will the waiting thread wake up, if a 3rd thread called wait() on this object?
is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)
What's happening if wait() will be called in the finalize() method?
When you call wait() from a thread, that thread stop executing and it's added to the waitset of the object. When you call notify() from another thread, a random thread from the waitset is waked up, if you call notifyAll() all would be ready to execute.
When you call notify(), the thread is ready to run but it doesnt mean it will be executed inmediately so be careful.
It would wake up a thread from the waitset randomly.
Youd don't know which one will be waked up first, it doesn't follow any order.
Thread.getState()
You would produce deadlock.
notify will wake one thread waiting on the monitor. Unless and until the monitor is unowned, no thread waiting can run; wait() must be called in a synchronized block and so the lock must be held to continue running that block.
No guarantees. Call notifyAll to give all threads a chance to wake.
Dunno. You could have the thread set a variable saying it's waiting before it goes to sleep...
This is probably a bad idea. Can you come up with a situation where this is necessary?
That's why you have the notify() and notifyAll() methods. The former wakes up one thread waiting on the object, the latter wakes up all threads. A waiting thread will not wake up if wait() is called in another thread.
No.
It's only possible to call thread.holdsLock(obj) to see if a thread holds the monitor lock on a particular object.
Don't call wait() in a finalize method.
2: Not necessarily. notify() wakes up one of the waiting threads. It might be the original one or the third one.
3: Using thread.getState() you can find out if a thread is waiting for an object, but I don't know if you can always find out which object this is, exactly.

Categories