1

I found this example of code that is likely to cause Deadlock on Oracle's official Java site.

public class Deadlock {
    static 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) {
        final Friend alphonse =
            new Friend("Alphonse");
        final Friend gaston =
            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();
    }
}

Can someone explain why it is likely to cause Deadlock?

When the first friend ("Alphonse") is run, it executes bow and also calls bowBack on the other friend. Somewhere while this is happening, the second friend ("Gaston") is run, it executes its own version of bow and calls bowBack on Alphonse. So where is there a deadlock? They are both calling their own versions of methods.

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

0 Answers0