Search code examples
javaconcurrencyscheduling

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?


Solution

  • 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.