Is it possible for a thread to Deadlock itself?

2020-01-29 03:20发布

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            
    }
}

20条回答
▲ chillily
2楼-- · 2020-01-29 04:22

According to Wikipedia, "A deadlock is a situation wherein two or more competing actions are each waiting for the other to finish, and thus neither ever does."

..."In computer science, Coffman deadlock refers to a specific condition when two or more processes are each waiting for each other to release a resource, or more than two processes are waiting for resources in a circular chain."

I think two or more are key words here if you stay strict to definition.

查看更多
【Aperson】
3楼-- · 2020-01-29 04:23

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.

查看更多
登录 后发表回答