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
}
}
No, because Java implements reentrancy. But please don't mix up concurrency and RMI like that. Synchronization in stubs is something completely different than remote objects that are internally synchronized.
When a thread enters the synchronized block, it checks if the current thread is the owner of the lock, and if it is, the the thread just proceeds without waiting.
So I don't think it is possible.
You write a thread which can receive messages from other threads telling it to, for example, terminate. You write code in the thread to monitor other threads and send them terminate messages and wait for a response. The thread would find itself in the list, send itself a message to terminate and wait for itself to terminate. If it wasn't written in a way which prioritised incoming messages over the wait state ...
If you stretch the definition of the term deadlock: a single thread can find itself blocked on a non-reentrant lock that it took earlier.
A deadlock is a form of resource starvation with an interaction between multiple threads.
When a thread gets into a state of resource staving itself, it is referred to a livelock which is similar to a deadlock, but not the same by definition.
An example of a livelock is using ReentrantReadWriteLock. Despite being reentrant on reading OR writing, it doesn't allow upgrading the lock from read to write.
results in the process blocking here
A related question is; can a thread get into a deadlock without creating additional threads. This is possible as there are background threads e.g. the finalizer thread, which can run user code in the background. This allows for the main thread and the finalizer thread to deadlock each other.
You can get yourself into a single thread Deadlock with ReentrantReadWriteLock. Write locks can acquire read locks but not the other way around. The following will block indefinitely.