in java tutorial i came to this simple example of a Deadlock, and for some reason can't figure out why it blocked
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());
System.out.println("Nice try " + this.name);
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();
}
}
let's look to some real exemple
run:
Alphonse: Gaston has bowed to me!
Gaston: Alphonse has bowed to me!
Nice try Gaston
Nice try Alphonse
so both Alphonse and Gaston, now running "bow()", each one at the end of the "bow()" trying to call "bowBack()" on each other, "bowBack()" is no static, thus Alphonse and Gaston have separated instance of this method, also "bowBack()" wasn't called before, thus it shouldn't be blocked. So why ther is a Deadlock.
In a tutorial http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html
it's explained as
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 why, to run "bowBack()" it should first wait the end of the "bow()", if they don't interfere with each other
Alphonse.bow()--->trying to call-->Gaston.bowBack()
Gaston.bow()--->trying to call-->Alphonse.bowBack()