In Deadlock section, Java SE 7 Tutorial, there is an example as shown below. I don’t understand why the main method can create 2 STATIC nested objects (actually it is defined as static nested class). It is said that there is no instance of any static class, right? Can anyone help me out? Thanks.
===========================================================================================
Alphonse and Gaston are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time. This example application, Deadlock, models this possibility:
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();
}
}
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.
From the Java tutorials: In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
You could remove Friend from inside Deadlock and have it as an outer class with no change in behaviour.
The ‘static’ refers to access to variables and methods in the outer class. Like static (class) methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.
I don’t think it says anywhere “that there is no instance of any static class”. An outer class can’t be static and a nested class is in effect an outer class.
Good question though – i recently went through this example and didn’t think about this.