This code comes from Oracle tutorial about concurrency. I don't understand why synchronizing methods leads to deadlock. When methods are not synchronized everything works fine, but when I add synchronized keyword, program stops and method bowBack() is never invoked. Could someone explain in affordable manner why it happens? Below is mentioned code snippet:
public class Deadlock {
static class Friend {
private final String name;
Friend(String name) {
this.name = name;
}
String getName() {
return this.name;
}
synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
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(() -> alphonse.bow(gaston)).start();
new Thread(() -> gaston.bow(alphonse)).start();
}
}
So both threads are blocked waiting for the other to release a lock.
Deadlock happens because threads are trying to acquire the same resources in different order.
You have two resources here - alphonse and gaston. Synchronized method bow acquires a lock on its own object, and then calls bowBack, which acquires a lock on the opposite object.
gaston, and prepares to acquire a lock on alphonsealphonse, and prepares to acquire a lock on gastonAt this point, both threads are waiting for one another to release the lock on their object. However, neither one is about to do that before acquiring the lock on the opposite object, thus causing a deadlock:

Above: each of the two turning cars has occupied its corner of the intersection, and is waiting to drive into the opposite corner of the intersection before vacating its own.
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