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 second call to lock() will wait on the thread that locked m to unlock it. Since it's the same thread, that will never happen and the thread will have effectively deadlocked itself. This is how to produce a deadlock within one thread, making what you ask about technically possible.
One process cannot hold a resource, yet be waiting for another resource that it is holding. So it is not possible to have a deadlock involving only one process.
Thread Deadlock A deadlock is when two or more threads are blocked waiting to obtain locks that some of the other threads in the deadlock are holding. Deadlock can occur when multiple threads need the same locks, at the same time, but obtain them in different order.
Between 2 threads of a process, deadlock possible . It is not possible to have a deadlock involving only one single process. The deadlock involves a circular “hold-and-wait” condition between two or more processes, so “one” process cannot hold a resource, it need to be waiting for another resource that it is holding.
Well, based on the definition of:
A deadlock is a situation wherein two or more competing actions are each waiting for the other to finish.
I would say that the answer is no - sure a thread can sit there waiting indefinitely for something, however unless two competing actions are waiting for each other it is by definition not a deadlock.
Unless someone explains to me how a single thread can be simultaneously waiting for two actions to finish?
UPDATE: The only possible situation that I can think of is some sort of message pump, where a thread processes a message that asks it to wait indefinitely for something to happen, where in fact that something will be processed by another message on the message pump.
This (incredibly contrived) scenario could possibly be technically called a deadlock.
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