Could someone please explain why the following code results in deadlock.
My understanding is that when alphonse(thread) run then it acquires lock on friend obj because it invokes bow() method but how come gaston(another thread) is able to acquires the lock on the same friend obj while the alphonse haven't finished/released the lock on friend obj.
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.println("invoked by " + name);
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
System.out.printf("finished by " + name);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
System.out.println("exiting bowBack()");
}
}
public static void main(String[] args) throws InterruptedException {
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();
}
}
alphonse.bow()
. To enter this method, thread 1 acquires the lock of alphonse, since the bow()
method is synchronized.gaston.bow()
. To enter this method, thread 2 acquires the lock of gaston, since the bow()
method is synchronized.gaston.bowBack()
. To enter this method, thread 1 needs to acquire the lock of gaston, since the bowBack()
method is synchronized. It waits until thread 2 has released the lock of gastonalphonse.bowBack()
. To enter this method, thread 2 needs to acquire the lock of alphonse, since the bowBack()
method is synchronized. It waits until thread 1 has released the lock of alphonseThe two threads end up waiting for each other. It's a deadlock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With