Is it technically possible for a thread in Java to deadlock itself?
I was asked this at an interview a while back and responded that it wasn’t possible but the interviewer told me that it is. Unfortunately I wasn’t able to get his method on how to achieve this deadlock.
This got me thinking and the only situation that I can think of is where you can have this happen is where you have an RMI server process which contained a method that calls itself. The line of code that calls the method is placed in a synchronized block.
Is that even possible or was the interviewer incorrect?
The source code I was thinking about was along these lines (where testDeadlock is running in an RMI server process)
public boolean testDeadlock () throws RemoteException {
synchronized (this) {
//Call testDeadlock via RMI loopback
}
}
The JVM only keeps track of the local thread that has the monitor, if the calling class makes an external call back in on itself the incoming call causes the original thread to deadlock itself.
You should be able to run this code to illustrate the idea
The output from the program looks like
Additionally the thread also dump shows the following
which indicates that the thread has indeed managed to lock itself