How a thread in a blocked state is caused by waiting for a JVM to block objects

I saw that there are different ways in which a thread can get into a blocked state. I am interested to know what exactly happens after the thread is blocked. How he returns to a neglected state. If it is locked by sleeping (time), then it will be moved to the execution queue after a few milliseconds. If it is locked during an I / O operation, it enters the execution queue as soon as it is done. how it gets into the runnable queue when it is waiting for objects to lock. how does he know that lock on the expected object is now available. Can someone explain the insides of how a blocked thread works on I / O. Please correct me if my understanding on any of the above topics is not appropriate.

thanks

+4
source share
3 answers

How does it get into the runnable queue when it waits for objects to lock?

If a thread is blocked due to an attempt to enter a synchronized block, the thread is automatically marked as executed when another thread (holding the lock) releases the lock, exiting the synchronized block of the same object.

If the current thread is blocked by calling someObject.wait() , the thread is "freed" when another thread calls someObject.notify() .

At the bytecode level, it looks like this:

 [load some object, obj, onto the operand stack] monitorenter // grab the lock // do stuff [load obj onto the operand stack again] monitorexit // release the lock 

If someone else holds the obj lock, the thread will hang on monitorenter until another thread calls monitorexit .

The exact details of how monitorenter and monitorexit should be implemented are not specified by JLS. That is, it depends on the JVM / OS.

See JLS Wait Sets and Notifications for more information .

+3
source

At a level close to the code, it looks like this:

Theme 1:

 Object mutex = new Object(); .... synchronized(mutex) { //lock to mutex is acquired. mutex.wait(); //lock to mutex is released. Thread is waiting for somebody to call notify(). doSomething(); } 

Theme 2:

 synchronized(Thread1.mutex) { //acquires the lock on mutex. //Can be done only after mutex.wait() is called from Thread1 // and the lock is released Thread1.mutex.notify(); // notifies Thread1 that it can be resumed. } 

In general, you should keep in mind that Thread.sleep () contains a resource lock, but Thread.wait () releases the locks and can be notified by other Threads.

0
source

AFAIK JVM uses its own threads. Thus, the non-JVM OS manages the flow schedule and context switching.

You can see the actual JVM source code. It's open.

0
source

Source: https://habr.com/ru/post/1336987/


All Articles