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

The online tutorial says

When Deadlock runs, it's extremely likely that both threads will block when they attempt to invoke bowBack. Neither block will ever end, because each thread is waiting for the other to exit bow.

But I don't see any interdependency here. Can anyone explain where the deadlock is?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
OneZero
  • 11,556
  • 15
  • 55
  • 92

1 Answers1

1

It's a classical deadlock, 2 threads + 2 locks.

1) Thread 1 locks alphonse and moves to lock gaston

2) Thread 2 locks gaston and moves to lock alphonse

3) Thread 1 reaches gaston but it is locked by Thread 2 and Thread1 blocks

4) Thread 2 reaches alphonse but it is locked by Thread 1 and it blocks

add a delay here to increase probability

public synchronized void bow(Friend bower)  {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275