When thread1 tries to access a synchronized method which has been locked by another thread2, then thread1 goes to blocked state from running state. I want to understand in detail how does thread2 goes from blocked to runnable state?
Does this transition happen ONLY once thread2 releases the lock? If yes, then how thread1 comes to know that thread2 has released the lock (Consider this just a simple scenario where we don't have wait & notify mechanism)?
At entry to a synchronized block of code, a thread will be blocked if the requested
object lock is not available. It becomes runnable again when the JVM grants it the
lock. When the thread will actually run again is another JVM decision. That's it.
Jim ... ...
BEE MBA PMP SCJP-6
Sujeet Kumar Jaiswal
Joined: Mar 07, 2010
Got it Jim... Just one more small query, its JVM who will grant the lock or the thread scheduler.
Joined: Jan 09, 2008
Good question. I don't really now if the scheduler is considered part of the JVM or not.
Thread scheduler is only going to decide which thread has to get the opportunity to run and will come into effect after the thread has been in the runnable state. So def. not the scheduler is what I feel..
Every object has a waitset associated with it. When a thread come to aquire the lock on a synchronised block , if the lock is unavailable(ie some other thread is executing the block) , it will be placed in the waitset. When the active thread finishes execution , it releases the lock and thread scheduler will pick a thread from the wait set (according to priority . which one will get its turn , is not in programmers scope if all are of same priority) , and that thread becomes runnable and will aquire the lock.
Threads block because they are waiting on object locks. They are not waiting
for access to synchronized code. A different thread can freely use the same
synchronized code to operate on a different object. It is when the requested
object lock is granted that a blocked thread once more becomes runnable.