0

Consider the Singleton :

public final class MySingleton {
    private static class Nested 
    {
        private static final MySingleton INSTANCE = new MySingleton();
    }

    private MySingleton() 
    {
        if (Nested.INSTANCE != null) 
        {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static MySingleton getInstance() 
    {
        return Nested.INSTANCE;
    }
}

I didn't put any locks , but why is this a thread safe solution for the Singleton problem ?

JAN
  • 21,236
  • 66
  • 181
  • 318
  • 1
    Why don't you use an `enum` instead? – Luiggi Mendoza Sep 11 '15 at 14:51
  • @LuiggiMendoza How?! – JimmyB Sep 11 '15 at 14:58
  • @HannoBinder [What is an efficient way to implement a singleton pattern in Java?](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java). Also [What is the best approach for using an Enum as a singleton in Java?](http://stackoverflow.com/questions/427902/what-is-the-best-approach-for-using-an-enum-as-a-singleton-in-java) – Pshemo Sep 11 '15 at 15:01
  • Ah. I overlooked that an `enum` can have fields and methods like a normal class. Still, I wouldn't use it for singletons (no inheritance &c. for enums). – JimmyB Sep 14 '15 at 10:04

1 Answers1

5

I didn't put any locks, but why is this a thread safe solution for the Singleton problem ?

Because class variables are initialized when their declaring classes are initialized and classes are initialized behind a lock. The process is described in the Detailed Initialization Procedure chapter of the Java Language Specification.

When your client code invokes getInstance, the corresponding thread will try to access Nested.INSTANCE. If Nested hasn't been initialized, the current thread will acquire an initialization lock for the class and initialize it. Part of the initialization process will initialize the final class field INSTANCE.

Note that in the example you have given, there is no point in having the Nested class be a holder for INSTANCE, you might as well have had the field in the MySingleton class.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724