Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is static inner class singleton thread safe [duplicate]

Tags:

java

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();
    }
} 
like image 489
huashui Avatar asked Jul 23 '13 01:07

huashui


People also ask

Why is static inner class singleton thread-safe?

It's thread-safe because the JVM handles lazily loading the nested class.

Is static inner class thread-safe?

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 static singleton 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.

Why does singleton pattern have static?

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.


2 Answers

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.

like image 199
Tom Hawtin - tackline Avatar answered Oct 04 '22 20:10

Tom Hawtin - tackline


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

like image 35
DaoWen Avatar answered Oct 04 '22 21:10

DaoWen