Is the Initialize-On-Demand idiom really necessary when implementing a thread safe singleton using static initialization, or would a simple static declaration of the instance suffice?
Simple declaration of instance as static field:
class Singleton
{
private static Singleton instance=new Singleton();
private Singleton () {..}
public static Singleton getInstance()
{
return instance;
}
}
vs
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
private Singleton () {..}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
I ask this because Brian Goetz recommends the 1st approach in this article:
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
while he suggests the latter in this article
http://www.ibm.com/developerworks/library/j-jtp03304/
Does the latter approach provide any benefits that the former doesn't?
Well what i can say These articles are 7-9 years old.
Now we have > Java 1.5 where we have power of enumeration enum. According to 'Josh Block' The best way to write a singleton is to write a Single Element enum
public enum MySingleton{
Singleton;
// rest of the implementation.
// ....
}
But for your question I guess there is no issue in using either of the implementations. I personaly prefer the first option because its straightforward, simple to understand.
But watch out for the loop holes that we can be able to create more objects of these class in the same JVM at the same time by serializing and deserializing the object or by making the clone of the object.
Also make the class final, because we can violate the singleton by extending the class.
In first approach your singleton will get created once you load Singleton class. In the other, it will get created once you call getInstance() method. Singleton class may have many reasons to get loaded before you call getInstance. So you will most likely initialize it much earlier when you actually use it and that defeats the purpose of lazy initialization. Whether you need lazy initialization is a separate story.
The simple declaration pattern constructs the singleton when when the class Singleton is loaded. The initialize-on-demand idiom constructs the singleton when Singeton.getInstance() is called -- i.e., when class SingetonHolder is loaded.
So these are the same except for time; the second option allows you delay initialization. When to choose one or the other depends on (among other things) how much work you are doing in Singleton's constructor. If it's a lot, you may see improved application startup time with initialization-on-demand.
That said, my advice is to try not to do too much there so that the simplest pattern works for you.
-dg
According to this post, the thread-safe singleton class should look as below. But I'm wondering whether there's a need to add volatile keyword to static CrunchifySingleton instance variable. Since if the instance is created and stored in CPU cache, at which time it is not written back to main memory, meanwhile, another thread invoke on getInstance() method. Will it incur an inconsistency problem?
public class CrunchifySingleton {
private static CrunchifySingleton instance = null;
protected CrunchifySingleton() {
}
// Lazy Initialization
public static CrunchifySingleton getInstance() {
if (instance == null) {
synchronized (CrunchifySingleton.class) {
if (instance == null) {
instance = new CrunchifySingleton();
}
}
}
return instance;
}
}
I echo #duffymo's comment above: lazy singletons are nowhere near as useful as they initially appear.
However, if you absolutely must use a lazily-instantiated singleton, the lazy holder idiom is much a easier way to achieve thread safety:
public final class CrunchifySingleton {
private static class Holder {
private static final CrunchifySingleton INSTANCE = new CrunchifySingleton();
}
private CrunchifySingleton() {}
static CrunchifySingleton getInstance() { return Holder.INSTANCE; }
}
Also, note that to be truly singleton, the class needs to prohibit both instantiation and subclassing - the constructor needs to be private, and the class needs to be final, respectively.
Yep, if your Singleton instance is not volatile or even if it is volatile but you are using sufficiently old JVM, there's no ordering guarantees for the operations in which the line
instance = new CrunchifySingleton();
decomposes with regard to the volatile store.
The compiler can then reorder these operations so that your instance is not null (because memory has been allocated), but is still uninitialized (because its constructor still hasn't been executed).
If you want to read more about the hidden problems around Double-Checked Locking, specifically in Java, see The "Double-Checked Locking is Broken" Declaration.
The lazy holder idiom is a nice pattern that generalizes well for general static field lazy loading, but if you need a safe and simple Singleton pattern, I'd recommend what Josh Bloch (from Effective Java fame) recommends - the Java Enum Singleton:
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
The code how you quoted it is broken in Java. Yes, you need volatile and at least Java 5 to make the double-checked idiom thread safe. And you should also add a local variable in your lazy initialization to improve performance. Read more about it here: https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
Yes, making volatile will gaurantee that every time any thread is trying to access your critical section of code, the thread reads the data from memory itself and not from hread cache.
You need volatile in this case but a better option is to use either an enum if it is stateless
enum Singleton {
INSTANCE;
}
however stateful singletons should be avoid every possible. I suggest you try creating an instance which you pass via dependency injection.
What real (i.e. practical) difference exists between a static class and a singleton pattern?
Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?
What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.
The true answer is by Jon Skeet, on another forum here.
A singleton allows access to a single
created instance - that instance (or
rather, a reference to that instance)
can be passed as a parameter to other
methods, and treated as a normal
object.
A static class allows only static
methods.
Singleton objects are stored in Heap, but static objects are stored in stack.
We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object
.
Singleton classes follow the OOP (object oriented principles), static classes do not.
We can implement an interface with a Singleton class, but a class's static methods (or e.g. a C# static class) cannot.
The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.
static classes are not for anything that needs state. It is useful for putting a bunch of functions together i.e Math (or Utils in projects). So the class name just gives us a clue where we can find the functions and nothing more.
Singleton is my favorite pattern and I use it to manage something at a single point. It's more flexible than static classes and can maintain it's state. It can implement interfaces, inherit from other classes and allow inheritance.
My rule for choosing between static and singleton:
If there is a bunch of functions that should be kept together, then static is the choice.
Anything else which needs single access to some resources, could be implemented as a singleton.
Static Class:-
You cannot create the instance of static class.
Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
We cannot pass the static class to method.
We cannot inherit Static class to another Static class in C#.
A class having all static methods.
Better performance (static methods are bonded on compile time)
Singleton:-
You can create one instance of the object and reuse it.
Singleton instance is created for the first time when the user requested.
You can create the object of singleton class and pass it to method.
Singleton class does not say any restriction of Inheritance.
We can dispose the objects of a singleton class but not of static class.
Methods can be overridden.
Can be lazy loaded when need (static classes are always loaded).
We can implement interface(static class can not implement interface).
A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.
Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.
In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.
Quick Example:
if( useD3D )
IRenderer::instance = new D3DRenderer
else
IRenderer::instance = new OpenGLRenderer
To expand on Jon Skeet's Answer
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.
Singletons are easier to work with when unit testing a class. Wherever you pass singletons as a parameter (constructors, setters or methods) you can instead substitute a mocked or stubbed version of the singleton.
Here's a good article:
http://javarevisited.blogspot.com.au/2013/03/difference-between-singleton-pattern-vs-static-class-java.html
Static classes
a class having all static methods.
better performance (static methods are bonded on compile time)
can't override methods, but can use method hiding. (What is method hiding in Java? Even the JavaDoc explanation is confusing)
public class Animal {
public static void foo() {
System.out.println("Animal");
}
}
public class Cat extends Animal {
public static void foo() { // hides Animal.foo()
System.out.println("Cat");
}
}
Singleton
an object that can only be instantiated once.
methods can be overridden (Why doesn't Java allow overriding of static methods?)
easier to mock then static methods
better at maintaining state
In summary, I would only use static classes for holding util methods, and using Singleton for everything else.
Edits
static classes are lazy loaded as well. Thanks #jmoreno
(When does static class initialization happen?)
method hiding for static classes. Thanks #MaxPeng.
Another advantage of a singleton is that it can easily be serialized, which may be necessary if you need to save its state to disc, or send it somewhere remotely.
I'm not a great OO theorist, but from what I know, I think the only OO feature that static classes lack compared to Singletons is polymorphism.
But if you don't need it, with a static class you can of course have inheritance ( not sure about interface implementation ) and data and function encapsulation.
The comment of Morendil, "The design style embodied in a static class is purely procedural" I may be wrong, but I disagree.
In static methods you can access static members, which would be exactly the same as singleton methods accessing their single instance members.
edit:
I'm actually thinking now that another difference is that a Static class is instantiated at program start* and lives throughout the whole life span of the program, while a singleton is explicitly instantiated at some point and can be destroyed also.
* or it may be instantiated at first use, depending on the language, I think.
To illustrate Jon's point what's shown below cannot be done if Logger was a static class.The class SomeClass expects an instance of ILogger implementation to be passed into its constructor.
Singleton class is important for dependency injection to be possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var someClass = new SomeClass(Logger.GetLogger());
}
}
public class SomeClass
{
public SomeClass(ILogger MyLogger)
{
}
}
public class Logger : ILogger
{
private static Logger _logger;
private Logger() { }
public static Logger GetLogger()
{
if (_logger==null)
{
_logger = new Logger();
}
return _logger;
}
public void Log()
{
}
}
public interface ILogger
{
void Log();
}
}
Singleton's are instantiated. It's just that there's only one instance ever created, hence the single in Singleton.
A static class on the other hand can't be instantiated.
Well a singleton is just a normal class that IS instantiated but just once and indirectly from the client code. Static class is not instantiated.
As far as I know static methods (static class must have static methods) are faster than non-static.
Edit:
FxCop Performance rule description:
"Methods which do not access instance data or call instance methods can be marked as static (Shared in VB). After doing so, the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that insures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."
I don't actually know if this applies also to static methods in static classes.
Main differences are:
Singleton has an instance/object while static class is a bunch of
static methods
Singleton can be extended e.g. through an interface while static
class can't be.
Singleton can be inherited which supports open/close principles in
SOLID principles on the other hand static class can't be inherited
and we need to make changes in itself.
Singleton object can be passed to methods while static class as it
does not have instance can't be passed as parameters
Distinction from static class
JDK has examples of both singleton and static, on the one hand java.lang.Math is a final class with static methods, on the other hand java.lang.Runtime is a singleton class.
Advantages of singleton
If your need to maintain state than singleton pattern is better choice than static class, because maintaining state in static class leads to bugs, especially in concurrent environment, that could lead to race conditions without adequate synchronization parallel modification by multiple threads.
Singleton class can be lazy loaded if its a heavy object, but static class doesn't have such advantages and always eagerly loaded.
With singleton, you can use inheritance and polymorphism to extend a base class, implement an interface and provide different implementations.
Since static methods in Java cannot be overridden, they lead to inflexibility. On the other hand, you can override methods defined in singleton class by extending it.
Disadvantages of static class
It is easier to write unit test for singleton than static class, because you can pass mock object whenever singleton is expected.
Advantages of static class
Static class provides better performance than singleton, because static methods are bonded on compile time.
There are several realization of singleton pattern each one with advantages and disadvantages.
Eager loading singleton
Double-checked locking singleton
Initialization-on-demand holder idiom
The enum based singleton
Detailed description each of them is too verbose so I just put a link to a good article - All you want to know about Singleton
Singleton is better approach from testing perspective.
Unlike static classes , singleton could implement interfaces and you can use mock instance and inject them.
In the example below I will illustrate this.
Suppose you have a method isGoodPrice() which uses a method getPrice() and you implement getPrice() as a method in a singleton.
singleton that’s provide getPrice functionality:
public class SupportedVersionSingelton {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
#Override
public int getPrice() {
// calculate price logic here
return 0;
}
}
Use of getPrice:
public class Advisor {
public boolean isGoodDeal(){
boolean isGoodDeal = false;
ICalculator supportedVersion = SupportedVersionSingelton.getInstance();
int price = supportedVersion.getPrice();
// logic to determine if price is a good deal.
if(price < 5){
isGoodDeal = true;
}
return isGoodDeal;
}
}
In case you would like to test the method isGoodPrice , with mocking the getPrice() method you could do it by:
Make your singleton implement an interface and inject it.
public interface ICalculator {
int getPrice();
}
Final Singleton implementation:
public class SupportedVersionSingelton implements ICalculator {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
#Override
public int getPrice() {
return 0;
}
// for testing purpose
public static void setInstance(ICalculator mockObject){
if(instance != null ){
instance = mockObject;
}
test class:
public class TestCalculation {
class SupportedVersionDouble implements ICalculator{
#Override
public int getPrice() {
return 1;
}
}
#Before
public void setUp() throws Exception {
ICalculator supportedVersionDouble = new SupportedVersionDouble();
SupportedVersionSingelton.setInstance(supportedVersionDouble);
}
#Test
public void test() {
Advisor advidor = new Advisor();
boolean isGoodDeal = advidor.isGoodDeal();
Assert.assertEquals(isGoodDeal, true);
}
}
In case we take the alternative of using static method for implementing getPrice() , it was difficult to the mock getPrice().
You could mock static with power mock, yet not all product could use it.
I'm agree with this definition:
The word "single" means single object across the application life
cycle, so the scope is at application level.
The static does not have
any Object pointer, so the scope is at App Domain level.
Moreover both should be implemented to be thread-safe.
You can find interesting other differences about: Singleton Pattern Versus Static Class
One notable difference is differed instantiation that comes with Singletons.
With static classes, it gets created by the CLR and we have not control on it.
with singletons, the object gets instantiated on the first instance it's tried to be accessed.
Below are some main differences between static class and singleton:
1.Singleton is a pattern, not a keyword like static. So for creating a static class static keyword is sufficient while in the case of singleton there is a need to write the logic for the singleton.
2.A singleton class must have a private default instance constructor, while a static class cannot contain any instance constructor.
3.A static class is neither instantiated nor extended, while a singleton class can be.
4.A static class is sealed implicitly, but the singleton class must be decorated as sealed explicitly.
5.It is possible for a singleton to implement the interface or inherit from another class, but the static class neither implements the interface nor extends from any other class.
6.We cannot implement the dependency injection with a static class, but DI is possible with the singleton class because it can be interface driven.
The scope of the static class is at the app domain level because it is managed by the CLR, while the scope of the singleton object is across the application lifecycle.
7.A static class cannot have any destructor but a singleton class can define a destructor.
8.The singleton class instance can be passed as a parameter to another method while a static class cannot be because it contains only static members.
Lazy Loading
Support of interfaces, so that separate implementation can be provided
Ability to return derived type (as a combination of lazyloading and interface implementation)
In many cases, these two have no practical difference, especially if the singleton instance never changes or changes very slowly e.g. holding configurations.
I'd say the biggest difference is a singleton is still a normal Java Bean as oppose to a specialized static-only Java class. And because of this, a singleton is accepted in many more situations; it is in fact the default Spring Framework's instantiation strategy. The consumer may or may not know it's a singleton being passed around, it just treat it like a normal Java bean. If requirement changes and a singleton needs to become a prototype instead, as we often see in Spring, it can be done totally seamlessly without a line of code change to the consumer.
Someone else has mentioned earlier that a static class should be purely procedural e.g. java.lang.Math. In my mind, such a class should never be passed around and they should never hold anything other than static final as attributes. For everything else, use a singleton since it's much more flexible and easier to maintain.
We have our DB framework that makes connections to Back end.To Avoid Dirty reads across Multiple users we have used singleton pattern to ensure we have single instance available at any point of time.
In c# a static class cannot implement an interface. When a single instance class needs to implement an interface for a business contracts or IoC purposes, this is where I use the Singleton pattern without a static class
Singleton provides a way to maintain state in stateless scenarios
Hope that helps you..
In an article I wrote I have described my point of view about why the singleton is much better than a static class:
Static class is not actually canonical class – it’s a namespace with functions and variables
Using static class is not a good practice because of breaking object-oriented programming principles
Static class cannot be passed as a parameter for other
Static class is not suitable for “lazy” initialization
Initialization and using of static class is always hard tracked
Implementing thread management is hard
Singleton class provides an object(only one instance) during the application lifeCycle such as java.lang.Runtime
While Static class only provide static methods such as java.lang.Math
Static methods in Java cannot be overridden, but methods defined in Singleton class can be overridden by extending it.
Singleton Class is capable of Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. whereas static not.
For eg: java.lang.Runtime,is a Singleton Class in Java, call to getRuntime() method returns the runtime object associated with the current Java application but ensures only one instance per JVM.
a. Serialization - Static members belong to the class and hence can't be serialized.
b. Though we have made the constructor private, static member variables still will be carried to subclass.
c. We can't do lazy initialization as everything will be loaded upon class loading only.
From a client perspective, static behavior is known to the client but Singleton behavior can be completed hidden from a client. Client may never know that there only one single instance he's playing around with again and again.
I read the following and think it makes sense too:
Taking Care of Business
Remember, one of the most important OO rules is that an object is responsible for itself. This means that issues regarding the life cycle of a class should be handled in the class, not delegated to language constructs like static, and so on.
from the book Objected-Oriented Thought Process 4th Ed.
We can create the object of singleton class and pass it to method.
Singleton class doesn't any restriction of inheritance.
We can't dispose the objects of a static class but can singleton class.
A recent question here had the following code (well, similar to this) to implement a singleton without synchronisation.
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Now, I think understand what this is doing. Since the instance is static final, it's built long before any threads will call getInstance() so there's no real need for synchronisation.
Synchronisation would be needed only if two threads tried to call getInstance() at the same time (and that method did construction on first call rather than at "static final" time).
My question is therefore basically: why then would you ever prefer lazy construction of the singleton with something like:
public class Singleton {
private Singleton() {}
private static Singleton instance = null;
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
My only thoughts were that using the static final method may introduce sequencing issue as in the C++ static initialisation order fiasco.
First off, does Java actually have this problem? I know order within a class is fully specified but does it somehow guarantee consistent order between classes (such as with a class loader)?
Secondly, if the order is consistent, why would the lazy construction option ever be advantageous?
Now, I think understand what this is doing. Since the instance is static final, it's built long before any threads will call getInstance() so there's no real need for synchronisation.
Not quite. It is built when the SingletonHolder class is initialized which happens the first time getInstance is called. The classloader has a separate locking mechanism, but after a class is loaded, no further locking is needed so this scheme does just enough locking to prevent multiple instantiation.
First off, does Java actually have this problem? I know order within a class is fully specified but does it somehow guarantee consistent order between classes (such as with a class loader)?
Java does have a problem where a class initialization cycle can lead to some class observing another class's static finals before they are initialized (technically before all static initializer blocks have run).
Consider
class A {
static final int X = B.Y;
// Call to Math.min defeats constant inlining
static final int Y = Math.min(42, 43);
}
class B {
static final int X = A.Y;
static final int Y = Math.min(42, 43);
}
public class C {
public static void main(String[] argv) {
System.err.println("A.X=" + A.X + ", A.Y=" + A.Y);
System.err.println("B.X=" + B.X + ", B.Y=" + B.Y);
}
}
Running C prints
A.X=42, A.Y=42
B.X=0, B.Y=42
But in the idiom you posted, there is no cycle between the helper and the singleton so there is no reason to prefer lazy initialization.
Now, I think understand what this is
doing. Since the instance is static
final, it's built long before any
threads will call getInstance() so
there's no real need for
synchronisation.
No. SingletonHolder class will be loaded only when you invoke SingletonHolder.INSTANCE for the very first time. final Object will become visible to other threads only after it is fully constructed. Such lazy initialization is called Initialization on demand holder idiom.
In Effective Java, Joshua Bloch notes that "This idiom … exploits the guarantee that a class will not be initialized until it is used [JLS, 12.4.1]."
The patern that you described works for two reasons
Class is loaded and initialized when first accessed (via SingletonHolder.INSTANCE here)
Class loading and initialization is atomic in Java
So you do perform lazy initialization in a thread safe and efficient way. This pattern is better alternative to double lock (not working) solution to synchronized lazy init.
You initialize eagerly because you don't have to write a synchronized block or method. This is mainly because synchronization is generally considered expensive
Just a little note about the first implementation: the interesting thing here is that class initialization is used to replace classical synchronization.
Class initialization is very well defined in that no code can ever get access to anything of the class unless it is fully initialized (i.e. all static initializer code has run). And since an already loaded class can be accessed with about zero overhead, this restricts the "synchronization" overhead to those cases where there is an actual check to be done (i.e. "is the class loaded/initialized yet?").
One drawback of using the class loading mechanism is that it can be hard to debug when it breaks. If, for some reason, the Singleton constructor throws an exception, then the first caller to getInstance() will get that exception (wrapped in another one).
The second caller however will never see the root cause of the problem (he will simply get a NoClassDefFoundError). So if the first caller somehow ignores the problem, then you'll never be able to find out what exactly went wrong.
If you use simply synchronization, then the second called will just try to instantiate the Singleton again and will probably run into the same problem (or even succeed!).
A class is initialized when it's accessed at runtime. So init order is pretty much the execution order.
"Access" here refers to limited actions specified in the spec. The next section talks about initialization.
What's going on in your first example is equivalently
public static Singleton getSingleton()
{
synchronized( SingletonHolder.class )
{
if( ! inited (SingletonHolder.class) )
init( SingletonHolder.class );
}
return SingletonHolder.INSTANCE;
}
( Once initialized, the sync block becomes useless; JVM will optimize it off. )
Semantically, this is not different from the 2nd impl. This doesn't really outshine "double checked locking", because it is double checked locking.
Since it piggybacks on class init semantics, it only works for static instances. In general, lazy evaluation is not limited to static instances; imagine there's an instance per session.
First off, does Java actually have this problem? I know order within a class is fully specified but does it somehow guarantee consistent order between classes (such as with a class loader)?
It does, but to a lesser degree than in C++:
If there is no dependency cycle, the static initialization occurs in the right order.
If there is a dependency cycle in the static initialization of a group of classes, then the order of initialization of the classes is indeterminate.
However, Java guarantees that default initialization of static fields (to null / zero / false) happens before any code gets to see the values of the fields. So a class can (in theory) be written to do the right thing irrespective of the initialization order.
Secondly, if the order is consistent, why would the lazy construction option ever be advantageous?
Lazy initialization is useful in a number of situations:
When the initialization has side effects that you don't want to happen unless the object is actually going to be used.
When the initialization is expensive, and you don't want it to waste time doing it unnecessarily ... or you want more important things to happen sooner (e.g. displaying the UI).
When the initialization depends on some state that is not available at static initialization time. (Though you need to be careful with this, because the state might not be available when lazy initialization gets triggered either.)
You can also implement lazy initialization using a synchronized getInstance() method. It is easier to understand, though it makes the getInstance() fractionally slower.
The code in the first version is the correct and best way to safely lazily construct a singleton.
The Java Memory Model guarantees that INSTANCE will:
Only be initialized when first actually used (ie lazy), because classes are loaded only when first used
Be constructed exactly once so it's completely thread-safe, because all static initialization is guaranteed to be completed before the class is available for use
Version 1 is an excellent pattern to follow.
EDITED
Version 2 is thread safe, but a little bit expensive and more importantly, severely limits concurrency/throughput
I'm not into your code snippet, but I have an answer for your question. Yes, Java has an initialization order fiasco. I came across it with mutually dependent enums. An example would look like:
enum A {
A1(B.B1);
private final B b;
A(B b) { this.b = b; }
B getB() { return b; }
}
enum B {
B1(A.A1);
private final A a;
B(A a) { this.a = a; }
A getA() { return a; }
}
The key is that B.B1 must exist when creating instance A.A1. And to create A.A1 B.B1 must exist.
My real-life use case was bit more complicated - the relationship between the enums was in fact parent-child so one enum was returning reference to its parent, but the second array of its children. The children were private static fields of the enum. The interesting thing is that while developing on Windows everything was working fine, but in production—which is Solaris—the members of the child array were null. The array had the proper size but its elements were null because they were not available when the array was instantiated.
So I ended up with the synchronized initialization on the first call. :-)
The only correct singletone in Java can be declared not by class, but by enum:
public enum Singleton{
INST;
... all other stuff from the class, including the private constructor
}
The use is as:
Singleton reference1ToSingleton=Singleton.INST;
All other ways do not exclude repeated instantiation through reflection or if the source of class is directly present in the app source. Enum excludes everything. ( The final clone method in Enum ensures that enum constants can never be cloned )