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.
Related
I am reading the book, "Core Java I" written by Cay H. Hostmann and he gives some information about the threads. He gives an example about threads and he gives a concrete banking example. As you know, in a bank, you may transfer funds, and he imagined that one fund transfer has implemented by one thread. At page 571 he wrote:
If the transfer method finds that sufficient funds are not available, it calls
"sufficientFunds.await();"
The current thread is now deactivated and gives up the lock. This lets in another thread that can, we hope, increase the account balance.
There is an essential difference between a thread that is waiting to acquire a lock and a thread that has called await. Once a thread calls the await method, it enters a wait set for that condition. The thread is not made runnable when the lock is available. Instead, it stays deactivated until another thread has called the signalAll method on the same condition. When another thread has transferred money, it should call
sufficientFunds.signalAll();
This call reactivates all
threads waiting for the condition. When the threads are removed from the wait set, they are again runnable and the scheduler will eventually activate them again. At that time, they will attempt to
reenter the object. As soon as the lock is available, one of them will acquire the lock and continue where it left off, returning from the call to await.
In the last paragraph, he mentioned: "reenter the object" (in bold). What does he mean? Also, he mentioned "returning from the call to await." Does he mean that the thread will start off from the point where await function calls?
Thanks in advance.
By “re-enter the object” he means the threads will try to execute the methods on the object (that are protected by the lock).
And yes, at the point it is signaled the waiting thread is still executing the await method, it never went anywhere. The thread went into a wait state where it doesn’t get scheduled to run, getting signaled wakes it up, then it has to acquire the lock in order to leave the await method.
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.
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.
Can someone please explain me the difference between Sleeping, Wait, Park, and Monitor thread states in VisualVM.
This is what I have found:
Running: thread is still running.
Sleeping: thread is sleeping (method yield() was called on the thread object)
Wait: thread was blocked by a mutex or a barrier, and is waiting for another thread to release the lock
Park: parked threads are suspended until they are given a permit. Unparking a thread is usually done by calling method unpark() on the thread object
Monitor: threads are waiting on a condition to become true to resume execution
What I am unable to understand is the state Park, what actually suspends the thread? How do I detect in the code what has made the thread suspend its execution?
Can someone please guide me in this regard.
Thanks.
I found a very nice diagram which pretty much describes all you need/want to know.
New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
Running
The thread is in running state if the thread scheduler has selected it.
Timed waiting
Timed waiting is a thread state for a thread waiting with a specified waiting time. A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:
Thread.sleep(sleeptime)
Object.wait(timeout)
Thread.join(timeout)
LockSupport.parkNanos(timeout)
LockSupport.parkUntil(timeout)
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
Terminated
A thread is in terminated or dead state when its run() method exits.
Hopefully this answers your question :).
Parking:
Disables the current thread for thread scheduling purposes unless the
permit is available.
Threads are being parked or suspended if you like to call it this way because it does not have a permission to execute. Once permission is granted the thread will be unparked and execute.
Permits of LockSupport are associated with threads (i.e. permit is given to a particular thread) and doesn't accumulate (i.e. there can be only one permit per thread, when thread consumes the permit, it disappears).
VisualVM maps the Java thread state (as described in #Maciej's answer) to the state presented in its UI as follows:
BLOCKED -> Monitor
RUNNABLE -> Running
WAITING/TIMED_WAITING -> Sleeping/Park/Wait (see below)
TERMINATED/NEW -> Zombie
Sleeping and Park are specific cases of (timed) waiting:
Sleeping: specifically waiting in Thread.sleep().
Park: specifically waiting in sun.misc.Unsafe.park() (presumably via LockSupport).
(The mapping is performed in ThreadMXBeanDataManager.java.)
A brief (and non-authoritative) discussion of Java thread state can be found here.
EDITED TO ADD:
It's also worth noting that threads blocking in calls to native methods appear in the JVM as RUNNABLE, and hence are reported by VisualVM as Running (and as consuming 100% CPU).
The documentation of selectorObj.select() method states
This method performs a blocking
selection operation. It returns only
after at least one channel is
selected, this selector's wakeup
method is invoked, or the current
thread is interrupted, whichever comes
first.
I understand the documentation
The thread that is blocked by select method, shouldn't be waiting? When I run profiler I see the thread is in run mode instead of wait state.
Although, I accept that, it is not mentioned that the thread should be in wait state, but my assumption is that till the signal dispatcher thread provides some input regarding any activity on channel registered with selector; the thread should be in wait state.
Please provide me some help as to why my assumption could be wrong.
When the thread is blocked in an I/O call, it is still running as far as Java thread is concerned.
Most profilers simply show thread state, which is defined as,
NEW A thread that has not yet started is in this state.
RUNNABLE A thread executing in the
Java virtual machine is in this
state.
BLOCKED A thread that is blocked
waiting for a monitor lock is in this
state.
WAITING A thread that is waiting
indefinitely for another thread to
perform a particular action is in
this state.
TIMED_WAITING A thread that is
waiting for another thread to perform
an action for up to a specified
waiting time is in this state.
TERMINATED A thread that has exited
is in this state.
As you can see, thread's WAITING/BLOCKED state has nothing to do with I/O.
Normally the select operation invokes the poll(...) system function.
select() provides the kernel with a list of file descriptors that it needs to monitor for read/write/error conditions as well as a timeout value. The kernel registers the process/thread with the associated channel's select function and puts the process/thread to sleep. Once the associated channel is ready or a timer has been expired, the kernel wakes up the registered process/thread. Note that this thread is the kernel thread and not the java application thread.
I do not see a reason for the thread doing select to be in WAIT state (Unless the implementation of the Selector returned by the Selector provider explicitly did a wait in the select() function).
It depends on the profiler. JProfiler shows the time when the selector thread is blocked on Selector.select() as "Network I/O". So, the best way to interpret the blocked Selector.select() as "Waiting for data".
Hope this helps.
Regards,
Slava Imeshev
Cacheonix In-Memory Data Grid