Boris Mitioglov
Boris Mitioglov

Reputation: 1182

why does java deadlock here?

I have an exaple from oracle.com, but I don't understand it.. Please, explain me. One thread run bow, then it run bowback but why nothing has printed?

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

Upvotes: 0

Views: 418

Answers (2)

JB Nizet
JB Nizet

Reputation: 691625

Here's a scenario leading to a deadlock:

  • thread 1 calls alphonse.bow() and thus gets alphonse's lock
  • thread 2 calls gaston.bow() and thus gets gaston's lock
  • thread 1 wants to call gaston.bowBack(), but blocks until gaston's lock is released
  • thread 2 wants to call alphonse.bowBack(), but blocks until alphonse's lock is released

So both threads wait for each other infinitely.

Upvotes: 3

user439793
user439793

Reputation:

Depends on the timing. Each thread enters bow, and locks that object to that thread. Then, inside that synchronized method, it attempts to call bowBack on the other object. But that method is synchronized, and the object is locked to the other thread. So both threads sit there waiting for the other object monitor to release, which never happens. Hence, deadlock.

Again, this really depends on timing. If the first thread finishes before the second one starts, it will work fine.

Upvotes: 3

Related Questions