Reputation: 1182
I have an exaple from oracle.com, but I don't understand it.. Please, explain me. One thread run bow, then it run bowback but why nothing has printed?
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();
}
}
Upvotes: 0
Views: 418
Reputation: 691625
Here's a scenario leading to a deadlock:
alphonse.bow()
and thus gets alphonse's lockgaston.bow()
and thus gets gaston's lockgaston.bowBack()
, but blocks until gaston's lock is releasedalphonse.bowBack()
, but blocks until alphonse's lock is releasedSo both threads wait for each other infinitely.
Upvotes: 3
Reputation:
Depends on the timing. Each thread enters bow, and locks that object to that thread. Then, inside that synchronized method, it attempts to call bowBack on the other object. But that method is synchronized, and the object is locked to the other thread. So both threads sit there waiting for the other object monitor to release, which never happens. Hence, deadlock.
Again, this really depends on timing. If the first thread finishes before the second one starts, it will work fine.
Upvotes: 3