why is static inner class singleton thread safe
It's thread-safe because the JVM handles lazily loading the nested class.
However, the code you posted doesn't seem to be using this pattern correctly (you shouldn't have a null check), and I think that actually breaks the thread safety. Here's a nice article where you can read more about why this pattern works and how to use it correctly:
Initialization-on-demand holder idiom
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.