The code you show is not technically thread-safe. This sort of dodgy code often gets mangles.
The code should look like:
public class Singleton {
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
Here we are assigning within a static initialiser (of SingletonHolder
), which will be seen by any thread accessing it with correct happens-before relationship. There's nothing really special about the nested class, it just allows the outer class to be used without immediately constructing the singleton object. Almost certainly this is entirely pointless, but it seems to please some people.
As ever [mutable] singletons are a really bad idea.