I have found the following example in Oracle's Java tutorial.
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();
}
}
They are claiming that 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 what I don't understand that when Bow() is a Synchronized method, then only one thread can access it at a time. So other threads cannot access Bow() while it is accessed by a threads. the thread using Bow() won't release the lock on Bow() until response from BowBack() comes back. Then how they are expecting Deadlock to happen? My understanding of Deadlock is when Synchronized Method A is depending on Method B and vice versa.And Thread1 gets lock on A() and Thread2 on B(), deadlock happens. but can anyone plz explain how the example explains the Deadlock scenario?