How to create thread safe Singleton in Java - Java Singleton Example (original) (raw)

Thread safe Singleton means a Singleton class that returns exactly the same instance even if exposed to multiple threads. Singleton in Java has been a classical design pattern like Factory method pattern, or Decorator design pattern and has been used a lot even inside JDK like java.lang.Runtime is an example of Singleton class. Singleton pattern ensures that exactly one instance of the class will remain in the Java program at any time. In our last post, 10 Interview questions on Singleton in Java we have discussed many different questions asked on Singleton pattern, One of them was writing Thread safe singleton in Java.

Prior to Java 5 double-checked locking mechanism is used to create a thread-safe singleton in Java which breaks if one Thread doesn't see an instance created by another thread at the same time and eventually you will end up with more than one instance of Singleton class.

From Java 5 onwards volatile variable guarantee can be used to write thread-safe singleton by using double-checked locking pattern. I personally don't prefer that way as there are many other simpler alternatives to write thread-safe singleton is available like using static field to initialize Singleton instance or using Enum as Singleton in Java. Let’s see examples of both ways to create thread-safe Singleton in Java.

Btw, In order to best understand design patterns, you need to work out some scenarios, examples, etc. It's best to get this kind of knowledge as part of your work but even if you don't get there, you can supplement them by these online design pattern courses and doing some object-oriented software design exercises.

How to create thread safe Singleton in Java - Java Singleton Example

Java Singleton Example – Thread-safe Singleton in Java using Enum

How to write thread safe Singleton in Java with exampleThis is one of the examples of Enum which I missed while writing 10 Examples of Enum in Java. Using Enum to create Singleton is by far the most simple and effective way to create thread-safe Singleton in Java, as the thread-safety guarantee is provided by the Java programming language itself.

You don't need to bother about the thread-safety issues. Since Enum instances are by default final in Java, it also provides safety against multiple instances due to serialization.

One point which is worth remembering is that, when we talk about thread-safe Singleton, we are talking about thread-safety during instance creation of Singleton class and not when we call any method of Singleton class.

If your Singleton class maintain any state and contains method to modify that state, you need to write code to avoid and thread-safety and synchronization issues. Any way here is code example of creating thread safe Singleton in Java using Enum.

public enum Singleton{
INSTANCE;

public void show(){
System.out.println("Singleton using Enum in Java");
}
}

//You can access this Singleton as Singleton.INSTANCE and call any method like below

Singleton.INSTANCE.show();

If this suits your need than this is the most easy way of writing thread-safe Singleton in Java. Using Enum as Singleton also provide couple of more benefits which you can find out on Why Enum Singleton are better in Java.

Java Singleton Example - Thread Safe Singleton using Static field Initialization

You can also create thread safe Singleton in Java by creating Singleton instance during class loading. static fields are initialized during class loading and Classloader will guarantee that instance will not be visible until its fully created. Here is example of creating thread safe singleton in Java using static factory method.

Only disadvantage of this implementing Singleton patter using static field is that this is not a lazy initialization and Singleton is initialized even before any clients call there getInstance() method.

public class Singleton{
private static final Singleton INSTANCE = new Singleton();

private Singleton(){ }

public static Singleton getInstance(){
return INSTANCE;
}
public void show(){
System.out.println("Singleon using static initialization in Java");
}
}

//Here is how to access this Singleton class

Singleton.getInstance().show();

here we are not creating Singleton instance inside getInstance() method instead it will be created by ClassLoader. Also, private constructor makes impossible to create another instance, except one case. You can still access private constructor by reflection and calling setAccessible(true). By the way You can still prevent creating another instance of Singleton by this way by throwing Exception from constructor.

That's all on how to create thread-safe Singleton in Java. Both the approach are safe with the thread-safety issue but my personal favorite is using Enum because of its simplicity, prevention of multiple instance against Serialization attack and concise code.

Other Java design pattern tutorials from Javarevisited Blog

> And lastly, one question for you? What is the best way to create Singleton in Java? Enum, Double checked locking, static singleton variable, holder pattern or anything else?