As the title said, why is static nested class singleton thread-safe?
public class Singleton {
private static class SingletonHolder {
public static Singleton instance;
public static Singleton getInstance() {
if (null == instance) {
instance = new Singleton();
}
}
}
public static Singleton getInstance() {
return SingletonHolder.getInstance();
}
}
It's thread-safe because the JVM handles lazily loading the nested class.
static methods and inner classes don't have any access to the variables of their dynamic counter part, and consequently can't use monitors/synchronize on an instance of their parent class. Of course this doesn't mean that declaring them and using them is inherently non-thread safe.
Is singleton thread safe? A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.
Singletons have a static property that you must access to get the object reference. So you are not instantiating an object such as in the manner we do for a normal class.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With