This is a question asked to one of my friends during an interview.
How do you know whether a thread is blocked inside a synchronized method, from another thread?
Can anybody please explain this using an example?
Using Thread.getState()
:
Thread.State state = getThreadInQuestion().getState();
if(state == Thread.State.BLOCKED) {
System.out.println("Blocked");
} else {
System.out.println("Not blocked");
}
Outside of a VM, you can use the jstack
tool to get full thread information for every thread, or connect to JMX and explore the Thread MBeans.
My short answer would be "no, not reliably".
Somebody mentioned checking for getState() == Thread.State.BLOCKED
. However, by the time you get the answer it may already be obsolete if the blocked thread is waiting on a monitor locked by a third thread, and the monitor gets released just as getState
is about to return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With