The first solution is (I believe) not thread-safe.
The second solution is (I believe) thread-safe, but might not work if you have complicated initialization dependencies in which MyClass.getInstance()
is called before the MyClass
static initializations are completed. That's probably the problem you were seeing.
Both solutions allow someone to create another instance of your (notionally) singleton class.
A more robust solution is:
class MyClass {
private static MyClass instance;
private MyClass() { }
public synchronized static MyClass getInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
}
In a modern JVM, the cost of acquiring a lock is miniscule, provided that there is no contention over the lock.
EDIT @Nate questions my statement about static initialization order possibly causing problems. Consider the following (pathological) example:
public ClassA {
public static ClassB myB = ClassB.getInstance();
public static ClassA me = new ClassA();
public static ClassA getInstance() {
return me;
}
}
public ClassB {
public static ClassA myA = ClassA.getInstance();
public static ClassB me = new ClassB();
public static ClassB getInstance() {
return me;
}
}
There are two possible initialization orders for these two classes. Both result in a static method being called before the method's classes static initialization has been performed. This will result in either ClassA.myB
or ClassB.myA
being initialized to null
.
In practice, cyclic dependencies between statics are less obvious than this. But the fact remains that if there is a cyclic dependency: 1) the Java compiler won't be able to tell you about it, 2) the JVM will not tell you about it. Rather, the JVM will silently pick an initialization order without "understanding" the semantics of what you are trying to do ... possibly resulting in something unexpected / wrong.
EDIT 2 - This is described in the JLS 12.4.1 as follows:
As shown in an example in §8.3.2.3, the fact that initialization code is unrestricted allows examples to be constructed where the value of a class variable can be observed when it still has its initial default value, before its initializing expression is evaluated, but such examples are rare in practice. (Such examples can be also constructed for instance variable initialization; see the example at the end of §12.5). The full power of the language is available in these initializers; programmers must exercise some care. ...