Is it possible for a thread to Deadlock itself?

后端 未结 20 1355
暗喜
暗喜 2020-12-02 09:29

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 inte

20条回答
  •  天命终不由人
    2020-12-02 09:43

    The interviewer was right. A thread can deadlock itself according to JCIP. But how?

    In the section 2.3.2 of the JCIP we have the following paragraph about Reentrancy:

    Reentrancy facilitates encapsulation of locking behavior, and thus simplifies the development of objectͲoriented concurrentcode. Without reentrantlocks, the very natural-looking code in Listing 2.7, in which a subclass overrides a synchronized method and then calls the super class method, would deadlock.

    The synchronized keyword's lock is a reentrant lock so a thread can lock and unlock in a nested manner but if you use a non-reentrant lock like the following example I wrote as a proof. You will have a deadlock! According to JCIP.

    public class SelfDeadLock {
    
    
        public static class Father{
            volatile protected int n = 0;
            protected Lock ourLock = new Lock();
    
            public void writeSth(){
                try {
                    ourLock.lock();
                    n++;
                    System.out.println("Father class: " + n);
                } catch (InterruptedException ex) {
                    Logger.getLogger(SelfDeadLock.class.getName()).log(Level.SEVERE, null, ex);
                }
                ourLock.unlock();
            }
        }
    
        public static class Child extends Father{
    
            @Override
            public void writeSth() {
                try {
                    ourLock.lock();
                    n++;
                    System.out.println("Child class: " + n);
                    super.writeSth();
                } catch (InterruptedException ex) {
                    Logger.getLogger(SelfDeadLock.class.getName()).log(Level.SEVERE, null, ex);
                }
                ourLock.unlock();
            }   
        }
    
        public static void main(String[] args) {
            Child child = new Child();
            child.writeSth();
        }
    }
    

提交回复
热议问题