0

Recently, I had a chance to review the material from the Java docs here. And it includes following code;

public class AnotherDeadlockCreator {

class Friend {

    private final String name;

    public Friend(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public synchronized void bow(Friend bower) {
        System.out.format("%s: %s"
            + "  has bowed to me!%n", 
            this.name, bower.getName());
        bower.bowBack(this);
    }

    public synchronized void bowBack(Friend bower) {
        System.out.format("%s: %s"
            + " has bowed back to me!%n",
            this.name, bower.getName());
    }
}

public static void main(String[] args) {

    AnotherDeadlockCreator obj = new AnotherDeadlockCreator(); 

    final AnotherDeadlockCreator.Friend alphonse =
        obj.new Friend("Alphonse");

    final AnotherDeadlockCreator.Friend gaston =
            obj.new Friend("Gaston");

    new Thread(new Runnable() {
        public void run() { alphonse.bow(gaston); }
    }).start();


    new Thread(new Runnable() {
        public void run() { gaston.bow(alphonse); }
    }).start();
}

}

In addition to that, I've read that nested class sync locks locked on the "this" of the nested class. Please refer the following;

Locking and synchronization between outer and inner class methods?

Now what I don't understand is - when we apply the above claim ( about nested class locks ) to the deadlock code , how this gonna most likely cause a deadlock? I mean if the threads access to synchronized methods of the nested class on different objects, how the deadlock will occur? Am I missing some important stuff?

Thanks.

Community
  • 1
  • 1
stdout
  • 2,471
  • 2
  • 31
  • 40

1 Answers1

0

bow() and bowBack() are synchronized on the same object which is the Friend instance: alphonse and gaston.

here is an example of the deadlock:

alphonse.bow(gaston) is invoked at time T. (alphonse synch started)
gaston.bow(alphonse) is invoked at time T + 1. (gaston synch started)
gaston.bowBack(alphonse) is invoked at time T + 2. (gaston synch already taken...waiting)
alphonse.bowBack(gaston) is invoked at time T + 3.  (alphonse synch already taken...waiting)

--DeadLock.

LiozM
  • 136
  • 7
  • Yes, definitely. But this should not cause the deadlock here. See, the objects called through two threads are different so they do have different scopes - not shared. Therefore the lock should not stop and wait for other to finish unless the methods are not static. – stdout Apr 01 '16 at 06:48