Static initializer and the Singleton pattern

Weiqi Gao weiqigao@networkusa.net
Fri Nov 9 07:46:00 GMT 2001


Hi,

The following bit of code was distilled from a bigger application that
exhibited a case of interference between the singleton pattern and
static initializers.  Contrary to the naive expectation, under Sun's JDK
this program prints 'false'.  And a check against the JVM spec confirms
that the behavior is the expected bahavior.

However, under gcj (Red Hat 7.0, GCC 3.0.2), the program behaves as
follows:

==========8<==========
[weiqi@gao] $ gcj -o Main --main=Main Main.java
[weiqi@gao] $ ./Main
true
[weiqi@gao] $ gcj -C Main.java
[weiqi@gao] $ gij Main
false
[weiqi@gao] $ gcj -o Main1 --main=Main Main.class A.class B.class
[weiqi@gao] $ ./Main
false
[weiqi@gao] $ javac Main.java
[weiqi@gao] $ java Main
false
==========8<==========

==========8<==========
// Main.java
class A {
    // A is a singleton.  The getInstance() method is even synchronized.
    private static A instance;
    public synchronized static A getInstance() {
        return (instance == null) ? (instance = new A()) : instance;
    }

    // A uses B
    private B b;
    private A() {
        b = new B();
    }
}

class B {
    // B caches the only instance of A
    public static A a = A.getInstance();
}

class Main {
    public static void main(String[] args) {
        System.out.println(A.getInstance() == B.a);
    }
}
==========8<==========

-- 
Weiqi Gao
weiqigao@networkusa.net



More information about the Java mailing list