0

I have a problem with understanding this particular deadlock example from the Oracle tutorial. I think I have a pretty good idea of what deadlocks are (I've seen plenty of examples where two final Object locks are created and one thread gains the first one and the second the other), but this one seems more complex.

Why exactly can't the bowBack() method be invoked without blocking the program? If the methods are synchronized on this - If I understand it correctly, this is practically how synchronized methods work - then the threads do not share a resource which would cause them to wait for one another.

Is it because if you try to invoke a synchronized method within another synchronized method, you need to be "the only thread" inside this outer method?

From what I gather, they both enter bow() simultaneously and all is fine until bowBack() is called...

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();
    }
}

1 Answers1

1

The important part here is that the parameter/argument is also locked, and the bowback method is invoked on another object, not on this.

If the line instead read this.bowback() everything would be fine, but it's anotherObject.bowback(), and that object tries to synchronize on itself, but is already locked by another thread.

HopefullyHelpful
  • 1,652
  • 3
  • 21
  • 37