Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one Java thread check the state of another one, e.g. whether the other one is blocked?

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?

like image 482
Ammu Avatar asked Jun 23 '11 08:06

Ammu


2 Answers

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.

like image 125
Rob Harrop Avatar answered Sep 24 '22 05:09

Rob Harrop


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.

like image 41
NPE Avatar answered Sep 23 '22 05:09

NPE