I was doing some research about singletons, specifically regarding lazy vs eager initialization of singletons.
An example of eager initialization:
public class Singleton { //initialzed during class loading private static final Singleton INSTANCE = new Singleton(); //to prevent creating another instance of Singleton private Singleton(){} public static Singleton getSingleton(){ return INSTANCE; } }
but as shown above that it is eager initialization and thread safety is left to jvm but now, I want to have this same pattern but with lazy initialization.
so I come up with this approach:
public final class Foo { private static class FooLoader { private static final Foo INSTANCE = new Foo(); } private Foo() { if (FooLoader.INSTANCE != null) { throw new IllegalStateException("Already instantiated"); } } public static Foo getInstance() { return FooLoader.INSTANCE; } }
As shown above Since the line
private static final Foo INSTANCE = new Foo();
is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.
Is this correct?
Lazy initialization is possible. It is also 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.
Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.
Singleton Class in Java using Lazy LoadingThe instance could be initialized only when the Singleton Class is used for the first time. Doing so creates the instance of the Singleton class in the JVM Java Virtual Machine during the execution of the method, which gives access to the instance, for the first time.
Your second code snippet is, in my opinion, the best way of thread-safe lazily initializing a singleton. It actually has a pattern name
Initialization-on-demand holder idiom
I would suggest you use it.
You first design is actually lazy. Think about it, the instance is only created when the class is initialized; the class is only initialized when the getSingleton()
method is called [1]. So the instance is only created when it's asked for, i.e. it's lazily created.
[1] http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1
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