Name: yyT116575 Date: 11/10/2000
This is a documentation error in question of the week 111
The solution to Question Of The Week 111 gives an invalid template for
implementing the singleton pattern. This is particularly problematical as the
error in the code is insidious. The code suggests this pattern:
class Singleton {
private final static theInstance=new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return theInstance;
}
}
But for correct operation this depends upon the instantiation of the singleton
instance happening as last thing in the textual set of static class initializers
(this is how the JLS defines the order of class initializers).
So if an implementation of the code looks like this:
class Singleton {
private static Singleton theInstance = new Singleton();
private static int theInt = 0xdeadbeef;
private int anotherInt;
private Singleton() {
anotherInt = theInt+1;
}
public static Singleton getInstance() {
return(theInstance);
}
public int getThatInt() {
return(anotherInt);
}
}
Then anotherInt will not have the correct value. As you can see, the error is
extremely insidious. Given the prevalence of usage of the singleton pattern you
should correct the implementation given in question of the week.
(Review ID: 112078)
======================================================================