I have seen there are different ways a thread could get to blocked state. I'm interested to know what exactly happens after a thread is in blocked state. How does it get back to running state?
If its blocked by sleep(time) then it moves to the runnable queue after time milli secs. If its blocked on a I/O operation it gets into the runnable queue once that is done.
How does it get to the runnable queue when it is waiting on an objects lock? How does it know that the lock on the object its waiting for is now available? Can some one also explain the internals of how the blocked thread on I/O works?
Please correct me if my understanding on any of the above topics isn't right..
If the thread is blocked due to trying to enter a
synchronized
block, the thread is automatically marked as runnable when the other thread (holding the lock) releases the lock by exiting from asynchronized
block of the same object.If the current thread is blocked due to a call to
someObject.wait()
, the thread is "released" when another thread callssomeObject.notify()
.On the bytecode level it looks as follows:
If someone else already holds the lock of
obj
, the thread will hang onmonitorenter
until the other thread callsmonitorexit
.The exact details of how
monitorenter
andmonitorexit
should be implement is not specified by the JLS. That is, it is JVM/OS dependent.For further details, refer to JLS Wait Sets and Notifications.