Java Singleton Pattern is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category.
From the definition, it seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns.
The implementation of Java Singleton pattern has always been a controversial topic among developers. Here we will learn about Singleton design pattern principles, different ways to implement the Singleton design pattern and some of the best practices for its usage.
Singleton Pattern
- Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
- The singleton class must provide a global access point to get the instance of the class.
- Singleton pattern is used for logging, drivers objects, caching and thread pool.
- Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.
- Singleton design pattern is used in core java classes also, for example
java.lang.Runtime
,java.awt.Desktop
.
Java Singleton Pattern Implementation
To implement a Singleton pattern, we have different approaches but all of them have the following common concepts.
- Private constructor to restrict instantiation of the class from other classes.
- Private static variable of the same class that is the only instance of the class.
- Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
In further sections, we will learn different approaches of Singleton pattern implementation and design concerns with the implementation.
1. Eager initialization
In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.
Here is the implementation of the static initialization singleton class.
package com.journaldev.singleton;
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections, etc. We should avoid the instantiation until unless client calls the getInstance
method. Also, this method doesn’t provide any options for exception handling.
2. Static block initialization
Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling.
package com.journaldev.singleton;
public class StaticBlockSingleton {
private static StaticBlockSingleton instance;
private StaticBlockSingleton(){}
//static block initialization for exception handling
static{
try{
instance = new StaticBlockSingleton();
}catch(Exception e){
throw new RuntimeException("Exception occured in creating singleton instance");
}
}
public static StaticBlockSingleton getInstance(){
return instance;
}
}
Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use. So in further sections, we will learn how to create a Singleton class that supports lazy initialization.
Read: Java static
3. Lazy Initialization
Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Here is the sample code for creating Singleton class with this approach.
package com.journaldev.singleton;
public class LazyInitializedSingleton {
private static LazyInitializedSingleton instance;
private LazyInitializedSingleton(){}
public static LazyInitializedSingleton getInstance(){
if(instance == null){
instance = new LazyInitializedSingleton();
}
return instance;
}
}
The above implementation works fine in case of the single-threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if condition at the same time. It will destroy the singleton pattern and both threads will get the different instances of the singleton class. In next section, we will see different ways to create a thread-safe singleton class.
4. Thread Safe Singleton
The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.
package com.journaldev.singleton;
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton(){}
public static synchronized ThreadSafeSingleton getInstance(){
if(instance == null){
instance = new ThreadSafeSingleton();
}
return instance;
}
}
Above implementation works fine and provides thread-safety but it reduces the performance because of the cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances (Read: Java Synchronization). To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of a singleton class is created.
The following code snippet provides the double-checked locking implementation.
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
Read: Thread Safe Singleton Class
5. Bill Pugh Singleton Implementation
Prior to Java 5, java memory model had a lot of issues and the above approaches used to fail in certain scenarios where too many threads try to get the instance of the Singleton class simultaneously. So Bill Pugh came up with a different approach to create the Singleton class using an inner static helper class. The Bill Pugh Singleton implementation goes like this;
package com.journaldev.singleton;
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
Notice the private inner static class that contains the instance of the singleton class. When the singleton class is loaded, SingletonHelper
class is not loaded into memory and only when someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.
This is the most widely used approach for Singleton class as it doesn’t require synchronization. I am using this approach in many of my projects and it’s easy to understand and implement also.
Read: Java Nested Classes
6. Using Reflection to destroy Singleton Pattern
Reflection can be used to destroy all the above singleton implementation approaches. Let’s see this with an example class.
package com.journaldev.singleton;
import java.lang.reflect.Constructor;
public class ReflectionSingletonTest {
public static void main(String[] args) {
EagerInitializedSingleton instanceOne = EagerInitializedSingleton.getInstance();
EagerInitializedSingleton instanceTwo = null;
try {
Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
//Below code will destroy the singleton pattern
constructor.setAccessible(true);
instanceTwo = (EagerInitializedSingleton) constructor.newInstance();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(instanceOne.hashCode());
System.out.println(instanceTwo.hashCode());
}
}
When you run the above test class, you will notice that hashCode of both the instances is not same that destroys the singleton pattern. Reflection is very powerful and used in a lot of frameworks like Spring and Hibernate, do check out Java Reflection Tutorial.
7. Enum Singleton
To overcome this situation with Reflection, Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. Since Java Enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization.
package com.journaldev.singleton;
public enum EnumSingleton {
INSTANCE;
public static void doSomething(){
//do something
}
}
Read: Java Enum
8. Serialization and Singleton
Sometimes in distributed systems, we need to implement Serializable interface in Singleton class so that we can store its state in the file system and retrieve it at a later point of time. Here is a small singleton class that implements Serializable interface also.
package com.journaldev.singleton;
import java.io.Serializable;
public class SerializedSingleton implements Serializable{
private static final long serialVersionUID = -7604766932017737115L;
private SerializedSingleton(){}
private static class SingletonHelper{
private static final SerializedSingleton instance = new SerializedSingleton();
}
public static SerializedSingleton getInstance(){
return SingletonHelper.instance;
}
}
The problem with serialized singleton class is that whenever we deserialize it, it will create a new instance of the class. Let’s see it with a simple program.
package com.journaldev.singleton;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class SingletonSerializedTest {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
SerializedSingleton instanceOne = SerializedSingleton.getInstance();
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
"filename.ser"));
out.writeObject(instanceOne);
out.close();
//deserailize from file to object
ObjectInput in = new ObjectInputStream(new FileInputStream(
"filename.ser"));
SerializedSingleton instanceTwo = (SerializedSingleton) in.readObject();
in.close();
System.out.println("instanceOne hashCode="+instanceOne.hashCode());
System.out.println("instanceTwo hashCode="+instanceTwo.hashCode());
}
}
The output of the above program is;
instanceOne hashCode=2011117821
instanceTwo hashCode=109647522
So it destroys the singleton pattern, to overcome this scenario all we need to do it provide the implementation of readResolve()
method.
protected Object readResolve() {
return getInstance();
}
After this, you will notice that hashCode of both the instances is same in the test program.
Read: Java Serialization and Java Deserialization.
I hope this article helps you in grasping fine details of Singleton design pattern, do let me know through your thoughts and comments.
Wonderful explanation, thank you so much!
Wrong way to implement double-lock.Instance = new ThreadSafeSingleton();It’s possible to reorder.Returns without initializing the object.
> Prior to Java 5, java memory model had a lot of issues and the above approaches used to fail in certain scenarios where too many threads try to get the instance of the Singleton class simultaneously.
Could you give an example?
How about we make the `instance` volatile? Will this avoid above issues?
“`
public class ThreadSafeSingleton {
private static volatile ThreadSafeSingleton instance;
private ThreadSafeSingleton(){}
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
}
“`
Hi Pankaj,
I follow your articles.
I think the below code is thread safe as the object will be created only once.
package com.journaldev.singleton;
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
Please clarify?
Thanks
Naidu
Which approach is preferred? DCC with volatile instance of singleton
OR
static inner helper class
Noticed the volatile instance case isn’t mentioned here
I recommend capitalizing “instance” in the eager initialization example, as it follows convention, but also drives home the point of the instance being final and created at class load.
if is condition not loop 🙂
haha, thanks for noticing it. I have corrected it.
if i use clone method then i copied it
why we declare it as static “private static StaticBlockSingleton instance”
what would go wrong if we declare it as non static
You must consider a multithreaded behaviour in order to obtain exact single(ton) instance. In Multithreaded environment, the instance created with static will ensure to have same thread stack irrespective of multiple thread instances created.
Many things can go wrong. I will not talk about all but the first and biggest issue would be that you will need and object to access the non-static variable which you will never have and getInstance is a static method and you can not access a non-static member without an object.
For Eager initialization methods, I do not think that there will be the mentioned issue if there are no other non-private static methods (or static fields) of the Singleton class other than getInstance method. As any class is only loaded when its constructor is called or any static method or field is accessed or it is loaded / instantiated using Reflection API, so our class will load only when getInstance is called. In most scenarios, Reflection is not used, so implementing eager initialization method should be an easy way to simulate Singleton pattern for most use cases.
Please clarify me why we cannot use exception handling in your eager Initialization example (very first case)
@Mayank try block can only be used for statements from method body or static initializer. We can not use it for variable declaration.
Hi Pankaj,
Thanks a lot for such a wonderful explanation.
Please clarify me that why we cannot write exception handling code (try-catch()) in the example given by you in eager initialization case (the very first case) to create singleton class.
your code about thread-safe singleton is wrong.
miss volatile
however, the link you given is correct.
please update your post.
Easy to understand Thanks nice explanation.
package com.singleton;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Demo1 implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static Demo1 obj = null;
private Demo1() {
}
protected Object readResolve() {
System.out.println(“read reslove called”);
return getInstance();
}
// if making synchronized then one thread will execute it at one time…//if
// performance of get instance
public static Demo1 getInstance() {
if (obj == null) {
System.out.println(“obj null”);
return new Demo1();
} else
return obj;
}
}
public class Demo {
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException {
Demo1 obj = Demo1.getInstance();
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(“abc.ser”));
out.writeObject(obj);
out.close();
ObjectInput in = new ObjectInputStream(new FileInputStream(“abc.ser”));
Demo1 obj1 = (Demo1) in.readObject();
System.out.println(obj.hashCode());
System.out.println(obj1.hashCode());
}
}
output :obj null
read reslove called
obj null
26253138
8860464
why hashcode different as i did readReslove()called
You implemented static factory method instead of a singleton pattern. Above getInstance method returns a new Singular object after every invocation, hence different hashcodes.
Replace with below snippet and thread unsafe singleton class is ready.
public static Singular getInstance() {
if (obj == null) {
System.out.println(“obj null”);
return obj=new Singular();
} else
return obj;
}
Thanks for finding the error!Now its working
Where you created Singular class?
Very nicely explained.
Good article
Thanks for this – good one.
Thank you so much for giving this kind of article for helping us a lot. Its very useful and helpful to understand various type to create the singleton classes.
Nice one!!
But you didn’t cover about cloning the singleton.
To avoid it you must override the clone method as below:
public Object clone() throws CloneNotSupportedException{
throw new CloneNotSupportedException(“Singleton, cannot be clonned”);
}
Not required. Since we are not implementing Cloneable.
give an example on Enum singleton
Nice examples, altough Enum singleton is awful in every way, it opposites to OOP and it looks like a bad trick.
import java.util.Scanner;
public enum EnumSingleton {
INSTANCE;
private EnumSingleton(){
scanner = new Scanner(System.in);
}
private Scanner scanner;
public Scanner getScanner(){
return scanner;
}
}
Thanks for the detailed explanation and good work.
You are the best !!!
Very nice explanation ..
I have use BillPughSingleton implement ion and try to destroy using reflection
and got exception as
java.lang.IllegalArgumentException: wrong number of arguments …
when i check .class file a one arg found
…
instanceTwo = (BillPughSingleton)constructor.newInstance(new Object[0]);
and its accept BillPughSingleton instance
Try this:
instanceTwo = (BillPughSingleton)constructor.newInstance();
In the case you can pass the already created instance of Singleton to avoid this Exception to see how reflection test failed for BullPughSingleton solution.
like below,
instance2 = (BillPughSingleton) constructor.newInstance(instance);
does BillPughSingleton supports multi-threaded env…?
yes a final variable is initialized once and remain same throughout its life-cycle.
Can we create singleton design pattern which can work in
multithreaded env and which can not be broken by reflection API ?
Throw an exception from private constructor should defeat serialization attack…
Meant to say reflection not serialization…
Bu if you throw exception from private constructor it will always throw excpetion and wont allow to create object of that class in any case , even single instance
Yeah EnumSingleton is perfect approach for it.
You will get “Class ReflectionEnumSingletonTest can not access a member of class EnumSingleton with modifiers “private”” error message during Reflection test.
Based on the number of bytecode instructions, synchronized method would cost less than synchronized block
————————————————————————————————————————
Java code
————————————————————————————————————————
package com.sangchual.java.exercise;
public class SynchronizedPerforamnce {
Integer counter = new Integer(0) ;
public synchronized void runWithSynchronizedMethod() {
counter ++ ;
}
public void runWithSynchronizedBlock() {
synchronized (this) {
counter ++ ;
}
}
}
————————————————————————————————————————
Bytecodes
————————————————————————————————————————
~/w/j/o/p/c/c/s/j/exercise javap -c SynchronizedPerforamnce.class
Compiled from “SynchronizedPerforamnce.java”
public class com.sangchual.java.exercise.SynchronizedPerforamnce {
java.lang.Integer counter;
public com.sangchual.java.exercise.SynchronizedPerforamnce();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object.””:()V
4: aload_0
5: new #2 // class java/lang/Integer
8: dup
9: iconst_0
10: invokespecial #3 // Method java/lang/Integer.””:(I)V
13: putfield #4 // Field counter:Ljava/lang/Integer;
16: return
public synchronized void runWithSynchronizedMethod();
Code:
0: aload_0
1: getfield #4 // Field counter:Ljava/lang/Integer;
4: astore_1
5: aload_0
6: aload_0
7: getfield #4 // Field counter:Ljava/lang/Integer;
10: invokevirtual #5 // Method java/lang/Integer.intValue:()I
13: iconst_1
14: iadd
15: invokestatic #6 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
18: dup_x1
19: putfield #4 // Field counter:Ljava/lang/Integer;
22: astore_2
23: aload_1
24: pop
25: return
public void runWithSynchronizedBlock();
Code:
0: aload_0
1: dup
2: astore_1
3: monitorenter
4: aload_0
5: getfield #4 // Field counter:Ljava/lang/Integer;
8: astore_2
9: aload_0
10: aload_0
11: getfield #4 // Field counter:Ljava/lang/Integer;
14: invokevirtual #5 // Method java/lang/Integer.intValue:()I
17: iconst_1
18: iadd
19: invokestatic #6 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
22: dup_x1
23: putfield #4 // Field counter:Ljava/lang/Integer;
26: astore_3
27: aload_2
28: pop
29: aload_1
30: monitorexit
31: goto 41
34: astore 4
36: aload_1
37: monitorexit
38: aload 4
40: athrow
41: return
Exception table:
from to target type
4 31 34 any
34 38 34 any
}
synchronized (this)
: you are locking your object itself, just like synchronized method. Create a dummy variable in the class and use that for synchronized block.If it would, it would do it for the few on only one thread in that case.
How are singleton object serialized even if object reference is static?
According to serialization, static variabal or object are not serialized
Very good explanation but I think you missed the concept of cloning, cloning can also break your singleton patten if you class is cloneable. Correct me if I am wrong.
Yes, so don’t implement Cloneable interface if you want to create a Singleton class.
Hi Pankaj,
I have a doubt in your Bill paugh Singleton implementation. You have stated that static nested class is not loaded into memory during class loading . But i have studied as static stuffs are always loaded with class initialization in JAVA. and they share with every class instance. Since in Bill paugh implemetation it is loaded only when we call getInstance method why ?
The classloader doesnot differentiate whether its a inner class or not.
Our concern here is when its initialized irrespective of when its loaded.
It is initialised when it is needed inside the getInstance().
INSTANCE will be creating on class loading?? I m confused about this.Please clear ..as per my understanding instance should be instantiated on class loading
Good Knowledge bro
Excellent explanation .Thank you.
Hi Pankaj,
This is very very helpful. I appreciate your knowledge.
Hi Pankaj,
Your way of explanation with examples is awesome.
Can you provide the example for “Enum Singleton”.
Thanks,
Murali
Very neat explanation and covered many ways to create singleton class.
Thank you.
Based on Pankaj’s Enum singleton above, you would call “doSomething()” like this:
package your.package.name;
import com.journaldev.singleton.EnumSingleton;
public class Client {
public static void main(String[] args) {
EnumSingleton.INSTANCE.doSomething(); // OR use class variable like below…
}
}
package your.package.name;
import com.journaldev.singleton.EnumSingleton;
public class Client {
private final EnumSingleton INST = EnumSingleton.INSTANCE;
public static void main(String[] args) {
INST.doSomething();
}
}
For the Enum Singleton, as it is an Enum type – you can implement but NOT extend classes, so consider that when choosing between what design to use for your Singletons.
helpful indeed! I got a clear idea about how can we implement singleton in different ways.
very good..keep posting such things
Very detailed and well explained sir, Thanks.
Well formatted, well organized, & Excellent tutorial on Singleton!!
Good explanation. Examples helped to understand each point
Thank you..!! 🙂
Awesome tutorial to get started with design patterns
Thanks a lot !
Hi,
I have written the simple program like below. It is not throwing any error even though I am creating object again in main method. Please let me know if we are able to create object again in main method what is the use of singleton.
package com.java.designpatterns;
public class SingletonPattern {
private static final SingletonPattern singletonPattern = new SingletonPattern();
private SingletonPattern(){}
public static SingletonPattern getInstance(){
return singletonPattern;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SingletonPattern singletonPattern = new SingletonPattern();
singletonPattern.getInstance();
System.out.println(“Hi”);
}
}
Dear Sasi,
You are creating the object of SingletonPattern in the same class hence you can access the private constructor which you have created in the same class. You should create a new test class to test whether it is allowing you to create a new object for SingletonPattern.
Try This,
class SingletonPattern {
private static final SingletonPattern singletonPattern = new SingletonPattern();
private SingletonPattern(){}
public static SingletonPattern getInstance(){
return singletonPattern;
}
}
Test class:
class Test
{
SingletonPattern singletonPattern = new SingletonPattern();// Error, since the constructor is private
singletonPattern.getInstance();
System.out.println(“Hi”);
}
Gotcha with method :
public Object readResolve()
{
return getInstance();
}
Only works in Single main thread. if you write serialized Singleton object in first program. In second program if you deserialize and try to readObject() then to get Singleton Object, But it will give you NULL object.
So this method won’t work across program or jvm
Best tutorial for design patterns!
It is best tutorial i have seen ever for design pattern……….
Initially i was surprise with the number of comments.
but could not stop myself to write this comment, It is really good article for singleton design pattern.
its Awesome explanation . it will be good if u add more lectures on
protected Object readResolve() {
return getInstance();
}
The following code doesn’t work, please help, thanks!
———————————————————————————————————–
public class SerializedSingleton implements Serializable{
private static final long serialVersionUID = -7604766932017737115L;
private SerializedSingleton(){}
private static class SingletonHelper{
private static final SerializedSingleton instance = new SerializedSingleton();
}
public static SerializedSingleton getInstance(){
return SingletonHelper.instance;
}
protected Object readResolve() {
return getInstance();
}
}
——————————————————————————————————-
Thanks!
Try to add throws ObjectStreamException to your readResolve method
even this giving 2 different objects.
Good but not video lecture
Excellent explanation . Even beginner will understands your explanation.
Keep it up.
very useful article .Easy to understand .
Bill Pugh Singleton Implementation, how it will resolve the double locking issue? if two threads accessing it first time ?
Very well explained! Hats off
Hi Guys,
How to use singleton in serialization…? & Which method we can use for singleton…?
Thanks,
Kirubakaran
It’s really great and simple article to understand. Thank you very much.
Thank you for you a series of greate article. May I ask why bill pugh singleton implementation is thread safe? Thnaks
It is because SingletonHelper class will be loaded only when we refer
SingletonHelper.instance;
and as class loading is thread-safe, static members initialization also happens only once and hence only one object is created though multiple threads call at the same time.
Since classsloader initializing the member, it is thread safe.
Write about clone method also.
Hi Vishwas,
If we are not implement singleton class with Cloneable interface then no one can create a clone object of the Singleton class.
If anyone trying to do clone() then it will throw CloneNotSupportedException.
Thanks, Brijesh.
In that case we never have lazy initialization with thread safe singleton ?
Hi Pankaj,
We can restrict the object creation by using Reflection by putting below piece of code in Constructor.
if(SingletonHelper.INSTANCE != null){
throw new RuntimeException(“Singleton already initialized”);
}
Or
if(!Thread.currentThread().getStackTrace()[2].getClassName().equals(“BillPughSingleton”)){
throw new RuntimeException(“Singleton already initialized”);
}
Can you please confirm Is this a correct approach to make a class singleton?
This is not a singleton. Because it will not return same object instead it throws exception. But that is not what singleton implementation.
I have written the singleton with the use of AtomicReference, for first few thread create multiple instance but getInstance() always return single object. For some senario we can use this also, there is no synchronization used.
import java.util.concurrent.atomic.AtomicReference;
public class SingleTon {
private static AtomicReference ref = new AtomicReference();
private SingleTon(){
}
public static SingleTon getInstance(){
SingleTon singleTon = ref.get();
if(singleTon == null){
SingleTon singleTon2 = new SingleTon();
if(ref.compareAndSet(null, singleTon2)){
return singleTon2;
}else {
singleTon = ref.get();
}
}
return singleTon;
}
public void test(){
System.out.println(“SingleTon.test()*******”);
}
}
It’s almost similar to double locking singleton method. There also synchronized is inside the if null check, so it will be used only once.
Reference variable of any singleton object would be Static type and as per my knowledge we can not serialize Static object. My question is how are we serializing an Static object??
Hi Pankaj,
Very nice article, covers all of the scenarios and approaches for creating Singleton object.
Thanks!
Hi Pankaj,
Can you please tell me Singleton example in jdk.
Pankaj,
Very informative article.
I think all the drawback of singleton can be eliminated by using ENUM ie , serialization, synchronization and reflection.
Simple and perfect demonstration !!
I think a pattern made of “Double checked Locking(DCL) with Volatile keyword” exists which has the features of Lazy loading, Multithreading and Singleton . It’s considered better than Bill pugh Singleton Implementation as Bill pugh’s Implementation is considered lazier than lazy Initialization! Please say a word on the difference between Bill pugh Implementation and DCL with volatile keyword.
thanks very good series of examples at single place,
When we read your website in mobile then gmail linkdin share option cover the page Content also please we resolve this problem because we due to this we are not able read website content properly.
can you take a snapshot and email me? the share icons in mobile are stick to the end of screen as horizontal bar and don’t cause any issue while reading article. Can you tell me which mobile you are using, so I can check?
Excellent writing, easy to understand. Thank you so much.
It’s awesome … very easy to understand
Thank you very much
which is better?
Hi Pankaj,
Great and nice Explanation.Easy to understood for beginners and experienced people.
i was not getting about enum singleton could you please give an example program
Quite a informative article and nice writing style. Keep it up.
What about multiple classloaders
This is very clear cut representation of Singleton Design Pattern.
Thank you very much Pankaj.
Very smooth and incremental explanation Pankaj. Great work 🙂
It is an extremely informative article !!
It is a very nice post for singleton design pattern with practical example for all the different kind of scenario.
Thanks Pankaj.
Provided explanation is excellent but the same time this code is not covering the clone scenario. It break the code.
Why Bill Pugh Singleton Implementation doesn’t require synchronization ?
Because in any tyqe of environment at any instance of time only one thread will make the call to getInstance() method and if it is not the very first call ( which will load the inner class and therefore create the INSTANCE first time ) the method returns already loaded same INSTANCE. In bill’s class getInstance() method has only one task – to return the INSTANCE.
Hi,
In Bill Pugh implementation, the approach is good, but what he has done is he created the instance as final to make it constant. samething we can do it in eagerly loaded or static initialization or even in synchronised one. what do u say.
This is one of the excellent explanation for the Singleton design pattern. Thanks Pankaj for details explanation.
Hi Pankaj,
Awesome article. Minor correction, private constructor was missed in Enum singleton.
Thanks,
Rasheed
There is no need of that. Enum definition. Java 5 onwards– Only one instance will be there like in the above examle the instance named as INSTANCE. you can use any other name e.g.
public enum EnumSingleton {
ONLYTHIS;
public static void doSomething(){
//do something
}
}
By default Enum constructor are private in java.
Very nice article with lot of scenarios covered. Thanks.
your article gave me great knowledge comparing to other..thanks & keep it up
All the approached greatly explained along with concern issues and benefits. Awesome article. Pankaj I personally appreciate your understanding. Best ever I had seen a Singleton article. Keep it up!!
Instance==null
Why you are doing in synchonize contex
Very Simple. Because if by this time the instance has not been created i.e ==null is true and lets say it is the very first thread executing the code, the thread has the lock (…is inside synchronized block ) it will create the instance. And if this not the very first thread, lets say it is the 2nd thread that now has acquired the lock it won’t create the instance instead it returns the already created one.
Very very nice explanation . I would have searched so many blogs but i find the best,this is yours. Thanks a lot.
Your the messiah for Java developers.
God bless you.
Dear Pankaj,
I always read your technical blogs, this is awesome explanation with all type of implementation, which really useful in long scale project. thank you so much for writing. keep it up.
God bless you.
Thanks,
Siva
Best example i ever got in whole internet.
thanks
Awesome article !!!!!!!!
Cool examples, Nice one, thanks for keeping it clean and simple
Really helpful post. Learnt basic concepts for singleton. 🙂
Awesome and complete article about singleton..Thanks a lot !!
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
This won’t work in case if initializing ThreadSafeSingleton is a heavy process and takes time to initialize.. any other thread may get half initialized object as the first check itself will say that ThreadSafeSingleton != null.
In a thread safe environment you should get or set the object by acquiring the lock.
For the rest of the article, it is very good…
Good Work Dude…
I like your posts. This one is really very nice.
Thanks for post.
🙂 It’s very helpful of me.
Good tutorial about singleton.I always get lot of confusion about this.Thanks for clarifying it out.
Hi Pankaj,
The above article was very good.
You have covered all the case for the implementation .
Are you planning to crate a vedio also.
Wish you a Happy new year and all the best 🙂
Regards,
Indrjeet Kumar
if (instance == null) {
synchronized (ThreadSafeSingleton.class) {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
}
}
This double checked locking code won’t work. If you write this code in Netbeans/ Intellij IDEA, it will show warning. Try to avoid this code.
ur examples are too good as usual
Wonderful article. Thanq.
here concept is good .but implementation is not that much good .pls try to give good stuff
I am not sure what else you are looking in the implementation examples, as far I see the comments here, people are liking it.
excelent explanation of singletone desine patteron
Hello Pankaj,
Like serialization, cloning can also destroy Singleton Pattern? Do you have any example or scenario to prevent object cloning on singleton class ?
To be able to clone an object it must (or a super class of it) specifically implement Cloneable interface. So generally if you are designing you won’t use Cloneable if you are creating a Singleton. But lets say your singleton is extending from a super class (that is the case some time) and if that super class has a public clone() method, then you should override it and make sure that it throws CloneNotSupportedException.
How distributed systems creates only one object where multiple clusters were involved
I am not sure my answer was good or not, but still I wanted to share my thoughts.
As multiple clusters involved I hope multiple JVMS will get involved one for each cluster. as there is no way the other JVM know about the object on the other one. so I think it is not possible to achieve what you are thinking.
Hi Anup,
you mean, how distributed systems uses only one object? if it is your question, i think we can serialize the object and share those object into distributed systems.
Can you please add a scenario how to prevent breaking Singleton using Reflection with an example.?
its good
Joshua Bloch also suggested , in case of SerializedSingleton we need to make all instance variables transient along with implemention of readResolve() method
Great article
AWESOME
Thanks for your blog, i have a doubt. actually not clear with, where and how to use below:
can you please explain with example?
protected Object readResolve() {
return getInstance();
}
To avoid the object creation while de-serialization process.
Can you please explain with an example?
How to avoid with this?
protected Object readResolve() {
return getInstance();
}
Great Article Buddy.. Thanks !!
if i call clone() method on Singleton object was it create new object or return existing one
if i load a class, using classloaders, is Singleton class has same behavior?
Could please explain on above….
try to implement the method with cloneable interface and override clone method by throwing clonenotsupported exception, so that the object will not be cloneable as well.
Thanks.
Implement Cloneable interface and Override clone method then return same object like the following:
class MySingleton implements Serializable,Cloneable{
private static MySingleton mySing = new MySingleton();
private MySingleton(){ }
public static MySingleton getinst(){
return mySing;
}
//Solution for Serialization
protected Object readResolve() {
return getinst();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return getinst();
}
}
Note: It also works for Serilization
Dear Lokesh, see this link
https://blog.yohanliyanage.com/2009/09/breaking-the-singleton/
The synchronized block of your code creating multiple objects in multi threaded programming
Sorry for post my previous info.it’s working fine
nice post..everything is discussed here…
in Singleton Class implements Serilizable, I added readResolve() method but still serialized object and deserialzed objects hashcodes are different…Please confirm me
Hi pankaj,
This is a nice article and almost everything is covered. it help me lot to understand singleton
its nice tutorial …………………..
@Anuj Agarwal
declaring INSTANCE as a final object restricts re – assignment of a new instance to it.
final Singleton INSTANCE = new Singleton();
INSTANCE = new Singleton(); // this won’t work
Hi Pankaj,
Thanks for the elaborate explanations.
I have a suggestion for you:
Can you please add a scenario whereby cloning of the Singleton object is explained with an example. It would definitely help to understand different situations where Singleton can be used.
Best Regards.
Thanks,
Nishant Kshirsagar
Great!!!!!
I love reading your tutorials. Great explaination !!!!
Awesome explanation and very clear thanks a ton to pankaj
This tutorial gave me good clarity on Singleton Pattern. Thank you.
This is the best one stop post for singleton pattern i’ve come across.I had to give a training and this post gave me everything to discuss.
Thanks a ton Pankaj for your amazing work.
Hi Pankaj,
your articles are very help to build concepts.
Could you please explain more about this statement of Bill Pugh approach: “This is the most widely used approach for Singleton class as it doesn’t require synchronization.”
Why this approach doesn’t require synchronization?
Because when you will call getInstane() method, the class will be loaded first in memory and an instance will get created. So even if multiple threads call getInstance() simultaneously, the class gets loaded only once and you dont need synchronization.
It means, in Bill Pugh Singleton Implementation approach, we dont need final keyword as used in below:
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
It will work fine in all scenarios even if we use it like :
private static BillPughSingleton INSTANCE = new BillPughSingleton();
You must declare INSTANCE as final for surety.
If you don’t then it will allow to change the value of INSTANCE in getInstance () method.
One can easily change the value for it in your getInstance () method as per below:
SingletonHelper.INSTANCE = null; // or by any value
So it is much sure for one to declaring it as final.
Thanks for your wonderful article
Hi Pankaj,
it is very nice post….one of the best among all intenet post on singleton
Really Nice that Sharing your Knowledge to e-learners
Very nice post…It was vry helpfull
Awesome post Pankaj…..This post is really very helpful…..Thank you
All the articles are very supporting. thanks
If you are using an enum as a singleton (only one enum constant “INSTANCE”), it is lazy loaded. If there are multiple enum constants, then they are all created at first access of any constant.
Awesome Work buddy !!!
Is Reflection breaks Bill Pugh Singleton Implementation?
I tried it does not create new instance, it throws IllegalArgumentException
But using serialization it breaks Bill Pugh Singleton Implementation. To avoid this we must use readResolve() method.
Is it right? if i did mistake please mention it….
Yes Reflection will break Bill Pugh implementation by making constructor accessible.
thanks…
Please look at this below code…… and tell the reason why it’s throwing IllegalArgumentException
import java.io.Serializable;
public class Singleton implements Serializable{
private static final long serialVersionUID = 2L;
private Singleton(){
System.out.println(“Singleton”);
}
public static Singleton getInstance(){
return Instance.s;
}
private static class Instance{
private static Singleton s = new Singleton();
}
protected Object readResolve(){
return Instance.s;
}
}
—————————————————————————————————————-
import java.lang.reflect.Constructor;
public class Test {
public static void main(String[] args) throws Exception {
Singleton s1 = Singleton.getInstance();
Singleton s2 = null;
try {
Constructor[] constructors = Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
constructor.setAccessible(true);
s2 = (Singleton) constructor.newInstance();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(s1);
System.out.println(s2);
}
}
————————————————————————————————————————-
output:
Singleton
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.vel.Test.main(Test.java:14)
com.vel.Singleton@106d69c
null
——————————————————————————————————————————
Note : if i remove readResolve() in Singleton class it does not throw any Exception. but I put this method it is throwing IllegalArguementException
Velmurugan, the method readResolve() works only when the object is read from Stream. This is not the case when you’re using Reflection to destroy the Singleton pattern.
but I am using readResolve() method, without implements Serializable interface at the time Reflection throws same Exception.
Is Reflection internally create an Object using Stream? or Internally any concept is going on in readResolve() method?
Please help me…… to understand
Hello, i copy/paste your code in my Eclipse. It works good and no IllegalArgumentException was launched
Can you please explain the Singleton enum prevents lazy loading ?I feel that the instance creation happens lazily when it is first accessed.
Enum variables are static by default, so as soon as you load an Enum all the variable instances will get loaded too. That’s why Enum can’t be used for lazy loading.
public enum SingletonEnum {
INSTANCE;
public static final String Id=”0″;
private SingletonEnum() {
System.out.println(“SingletonEnum initialized”);
}
public void execute (String arg) {
// Perform operation here
}
}
class Snippet {
public static void main(String[] args) {
System.out.println(SingletonEnum.Id);
}
}
Example to say enum approach is lazy loaded.
Hi Pankaj,
Really nice explanation.
Could you please let us know the other scinarios also where singleton is not a singleton.
like, cloning, how distributed systems creates only one object where multiple clusters were involved,
etc…
Thanks in advance,….
Very nice, explained in simple terms.
Very nice tutorial.
It help me lot to understand the singleton.
Could you please help me how protected Object readResolve() method make i class a singleton.
This is a nice article and almost everything is covered. Thanks a ton.
Very good site for design patterns. Explanation is easy and up to the mark. Thanks.
Hi Pankaj,
Can we create more than one object of a singleton class using serialization ?
Please provide your view in detail about in which condition Singleton classes can have more than one objects.
Thanks in advance.
Regards,
H Singh
Yes we can and thats why we can have readResolve() method implementation to get the same instance.
What is the purpose of readResolve() method? how it helps in maintaining only one object of singleton class.
can you tell in which class we can find viewResolve().
This web site useful for me, Thanks a ton.
Sir,
As per u provide contains which one is the best practices for the Singleton Pattern.
Regards
Vishnu
It depends on the situation, if your singleton is not heavyweight I would prefer pre-initialization but if you want lazy init, then I prefer helper inner class or Enum for singleton.
But you’d written that enum Singleton is not lazy loaded. So can you say enum singleton is lazy or not?
nice tutorial thanks …..
i have one question fro you
How annotations works internally?
Very nice post:-) keep up the good work
owesome post…evrything is discussed about singleton.keep it up….nd thanks
Thanks Poonam, glad you liked it.
what is difference between singleton and static method
singleton is a design pattern and static is a key word in JAVA