Recently, I had a chance to review the material from the Java docs here. And it includes following code;
public class AnotherDeadlockCreator {
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) {
AnotherDeadlockCreator obj = new AnotherDeadlockCreator();
final AnotherDeadlockCreator.Friend alphonse =
obj.new Friend("Alphonse");
final AnotherDeadlockCreator.Friend gaston =
obj.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();
}
}
In addition to that, I've read that nested class sync locks locked on the "this" of the nested class. Please refer the following;
Locking and synchronization between outer and inner class methods?
Now what I don't understand is - when we apply the above claim ( about nested class locks ) to the deadlock code , how this gonna most likely cause a deadlock? I mean if the threads access to synchronized methods of the nested class on different objects, how the deadlock will occur? Am I missing some important stuff?
Thanks.