Java Singleton Design Pattern Best Practices with Examples

Filed Under: Design Patterns
Singleton Pattern

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.

Comments

  1. Jiabin says:

    > 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;
    }
    }
    “`

  2. Naidu says:

    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

  3. Heena says:

    Which approach is preferred? DCC with volatile instance of singleton

    OR

    static inner helper class

    Noticed the volatile instance case isn’t mentioned here

  4. Jeremiah says:

    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.

  5. Sajal Gupta says:

    if is condition not loop 🙂

    1. Pankaj says:

      haha, thanks for noticing it. I have corrected it.

  6. Sunny says:

    why we declare it as static “private static StaticBlockSingleton instance”
    what would go wrong if we declare it as non static

    1. Chandrakanth C says:

      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.

    2. Hemant Chhonkar says:

      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.

  7. Shailesh says:

    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.

  8. Mayank Mishra says:

    Please clarify me why we cannot use exception handling in your eager Initialization example (very first case)

    1. Suryakant Sapkal says:

      @Mayank try block can only be used for statements from method body or static initializer. We can not use it for variable declaration.

  9. Mayank Mishra says:

    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.

  10. Ethan says:

    your code about thread-safe singleton is wrong.
    miss volatile

    however, the link you given is correct.

    please update your post.

  11. Akash says:

    Easy to understand Thanks nice explanation.

  12. pankaj says:

    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

    1. Bathula says:

      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;
      }

      1. pankaj says:

        Thanks for finding the error!Now its working

        1. Ambika Solanki says:

          Where you created Singular class?

  13. Wasim says:

    Very nicely explained.

  14. Pooja says:

    Good article

  15. Sandeep says:

    Thanks for this – good one.

  16. Patel says:

    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.

  17. Nitin says:

    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”);
    }

    1. Bibhav says:

      Not required. Since we are not implementing Cloneable.

  18. uday says:

    give an example on Enum singleton

  19. FStarred says:

    Nice examples, altough Enum singleton is awful in every way, it opposites to OOP and it looks like a bad trick.

    1. Marko says:

      import java.util.Scanner;

      public enum EnumSingleton {
      INSTANCE;

      private EnumSingleton(){
      scanner = new Scanner(System.in);
      }

      private Scanner scanner;

      public Scanner getScanner(){
      return scanner;
      }

      }

  20. Ugur says:

    Thanks for the detailed explanation and good work.

  21. MIsa says:

    You are the best !!!

  22. Neetesh says:

    Very nice explanation ..

  23. Dattatray says:

    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

    1. Gaurav Jain says:

      Try this:
      instanceTwo = (BillPughSingleton)constructor.newInstance();

    2. Bibhav says:

      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);

  24. Manish Kumar Prasad says:

    does BillPughSingleton supports multi-threaded env…?

    1. rohit saroha says:

      yes a final variable is initialized once and remain same throughout its life-cycle.

  25. Manish Kumar Prasad says:

    Can we create singleton design pattern which can work in
    multithreaded env and which can not be broken by reflection API ?

    1. Barba of the Pale Horse says:

      Throw an exception from private constructor should defeat serialization attack…

      1. Barba of the Pale Horse says:

        Meant to say reflection not serialization…

      2. GauravD says:

        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

    2. Bibhav says:

      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.

  26. Sangchual Cha says:

    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
    }

    1. Pankaj says:

      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.

    2. Rakesh Yadav says:

      If it would, it would do it for the few on only one thread in that case.

  27. Lakhan says:

    How are singleton object serialized even if object reference is static?
    According to serialization, static variabal or object are not serialized

  28. Kuldeep Singh says:

    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.

    1. Pankaj says:

      Yes, so don’t implement Cloneable interface if you want to create a Singleton class.

  29. Tejas says:

    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 ?

    1. Disha says:

      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().

      1. pankaj says:

        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

  30. Asutosh Swain says:

    Good Knowledge bro

  31. m&m says:

    Excellent explanation .Thank you.

  32. Devendra Singh says:

    Hi Pankaj,

    This is very very helpful. I appreciate your knowledge.

  33. Murali Krishna Varanasi says:

    Hi Pankaj,

    Your way of explanation with examples is awesome.

    Can you provide the example for “Enum Singleton”.

    Thanks,
    Murali

    1. rama devi says:

      Very neat explanation and covered many ways to create singleton class.

      Thank you.

    2. Joseph Grigg says:

      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.

  34. sourab wasnik says:

    helpful indeed! I got a clear idea about how can we implement singleton in different ways.

  35. nitin says:

    very good..keep posting such things

  36. Babanna S Duggani says:

    Very detailed and well explained sir, Thanks.

  37. Neetu says:

    Well formatted, well organized, & Excellent tutorial on Singleton!!

  38. amit ghorpade says:

    Good explanation. Examples helped to understand each point

  39. Janaksinh M says:

    Thank you..!! 🙂

  40. Awesome tutorial to get started with design patterns

    Thanks a lot !

  41. sasi says:

    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”);
    }

    }

    1. sai kumar says:

      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”);
      }

  42. Balaji says:

    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

  43. Kanij Sheikh says:

    Best tutorial for design patterns!

  44. Prashant Bagade says:

    It is best tutorial i have seen ever for design pattern……….

  45. Anupkumar Mahamalla says:

    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.

    1. satya says:

      its Awesome explanation . it will be good if u add more lectures on
      protected Object readResolve() {
      return getInstance();
      }

  46. Eddy says:

    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!

    1. Mehdi MAHMOUD says:

      Try to add throws ObjectStreamException to your readResolve method

      1. Manish Kumar Prasad says:

        even this giving 2 different objects.

  47. AUR Dogar says:

    Good but not video lecture

  48. umamaheswararao says:

    Excellent explanation . Even beginner will understands your explanation.
    Keep it up.

  49. priyanka says:

    very useful article .Easy to understand .

  50. prakash agarwalla says:

    Bill Pugh Singleton Implementation, how it will resolve the double locking issue? if two threads accessing it first time ?

  51. Keval Solanki says:

    Very well explained! Hats off

  52. kirubakaran says:

    Hi Guys,

    How to use singleton in serialization…? & Which method we can use for singleton…?
    Thanks,
    Kirubakaran

  53. Anil kumar says:

    It’s really great and simple article to understand. Thank you very much.

  54. Charlie says:

    Thank you for you a series of greate article. May I ask why bill pugh singleton implementation is thread safe? Thnaks

    1. GOPINATH M B says:

      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.

  55. Vishwas Tyagi says:

    Write about clone method also.

    1. Brijesh Baser says:

      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.

      1. Vishwas Tyagi says:

        Thanks, Brijesh.

  56. Sujeet says:

    In that case we never have lazy initialization with thread safe singleton ?

  57. Rakesh kumar Swain says:

    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?

    1. Krishna Chowdary Garapati says:

      This is not a singleton. Because it will not return same object instead it throws exception. But that is not what singleton implementation.

  58. Brijesh Baser says:

    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()*******”);
    }
    }

    1. Pankaj says:

      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.

  59. Sameer Patel says:

    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??

  60. Lalit says:

    Hi Pankaj,

    Very nice article, covers all of the scenarios and approaches for creating Singleton object.

    Thanks!

  61. panky031 says:

    Hi Pankaj,
    Can you please tell me Singleton example in jdk.

  62. Rizwan says:

    Pankaj,
    Very informative article.
    I think all the drawback of singleton can be eliminated by using ENUM ie , serialization, synchronization and reflection.

  63. Sindhura says:

    Simple and perfect demonstration !!

  64. Rajeev says:

    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.

  65. shailesh singh says:

    thanks very good series of examples at single place,

  66. Dndnnz says:

    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.

    1. Pankaj says:

      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?

  67. Surya says:

    Excellent writing, easy to understand. Thank you so much.

  68. Nagarjuna Aluru says:

    It’s awesome … very easy to understand

  69. mehdi says:

    Thank you very much
    which is better?

  70. Harish Kumar Tharala says:

    Hi Pankaj,
    Great and nice Explanation.Easy to understood for beginners and experienced people.

  71. siva kumar says:

    i was not getting about enum singleton could you please give an example program

  72. Anurag says:

    Quite a informative article and nice writing style. Keep it up.

  73. Raja says:

    What about multiple classloaders

  74. Amsidh Lokhande says:

    This is very clear cut representation of Singleton Design Pattern.

    Thank you very much Pankaj.

  75. Mohit Garg says:

    Very smooth and incremental explanation Pankaj. Great work 🙂

  76. Vasudha Singal says:

    It is an extremely informative article !!

  77. Himansu says:

    It is a very nice post for singleton design pattern with practical example for all the different kind of scenario.
    Thanks Pankaj.

  78. Prasann Mishra says:

    Provided explanation is excellent but the same time this code is not covering the clone scenario. It break the code.

  79. Ravi says:

    Why Bill Pugh Singleton Implementation doesn’t require synchronization ?

    1. Arvind Ajimal says:

      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.

      1. John says:

        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.

  80. Bharat says:

    This is one of the excellent explanation for the Singleton design pattern. Thanks Pankaj for details explanation.

  81. Rasheed says:

    Hi Pankaj,
    Awesome article. Minor correction, private constructor was missed in Enum singleton.

    Thanks,
    Rasheed

    1. Arvind Ajimal says:

      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
      }
      }

      1. Manish Kumar says:

        By default Enum constructor are private in java.

  82. Gayatri says:

    Very nice article with lot of scenarios covered. Thanks.

  83. Suresh reddy says:

    your article gave me great knowledge comparing to other..thanks & keep it up

  84. Rishi says:

    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!!

  85. hamid says:

    Instance==null
    Why you are doing in synchonize contex

    1. Arvind Ajimal says:

      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.

  86. Rasmita says:

    Very very nice explanation . I would have searched so many blogs but i find the best,this is yours. Thanks a lot.

  87. Kiran Panda says:

    Your the messiah for Java developers.
    God bless you.

  88. Sivamurugan Subramaniam (Siva) says:

    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

  89. Anil says:

    Best example i ever got in whole internet.
    thanks

  90. Harriesh says:

    Awesome article !!!!!!!!

  91. kinglee says:

    Cool examples, Nice one, thanks for keeping it clean and simple

  92. neeraj goyal says:

    Really helpful post. Learnt basic concepts for singleton. 🙂

  93. Swapnil says:

    Awesome and complete article about singleton..Thanks a lot !!

  94. Priyanka says:

    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…

  95. Paras says:

    Good Work Dude…

  96. Anuj Pankaj says:

    I like your posts. This one is really very nice.

  97. Daniel Lim says:

    Thanks for post.

    🙂 It’s very helpful of me.

  98. Surya says:

    Good tutorial about singleton.I always get lot of confusion about this.Thanks for clarifying it out.

  99. indrjeet kumar says:

    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

  100. Anoop says:

    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.

  101. Neeraj says:

    ur examples are too good as usual

  102. subrahmanyam says:

    Wonderful article. Thanq.

  103. sudheer.maguluri says:

    here concept is good .but implementation is not that much good .pls try to give good stuff

    1. Pankaj says:

      I am not sure what else you are looking in the implementation examples, as far I see the comments here, people are liking it.

      1. Phool Chand Nishad says:

        excelent explanation of singletone desine patteron

  104. Pawan Bhawsar says:

    Hello Pankaj,

    Like serialization, cloning can also destroy Singleton Pattern? Do you have any example or scenario to prevent object cloning on singleton class ?

    1. Arvind Ajimal says:

      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.

  105. Anup Kumar Shrivastava says:

    How distributed systems creates only one object where multiple clusters were involved

    1. suman says:

      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.

    2. Mohan says:

      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.

  106. SivaPrasad says:

    Can you please add a scenario how to prevent breaking Singleton using Reflection with an example.?

  107. Ramakrisha says:

    its good

  108. Abhijeet Kedare says:

    Joshua Bloch also suggested , in case of SerializedSingleton we need to make all instance variables transient along with implemention of readResolve() method

  109. Preeti says:

    Great article

  110. Sridhar says:

    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();
    }

    1. Priyank says:

      To avoid the object creation while de-serialization process.

      1. Manish Kumar says:

        Can you please explain with an example?
        How to avoid with this?

        protected Object readResolve() {
        return getInstance();
        }

  111. Manav says:

    Great Article Buddy.. Thanks !!

  112. lokesh says:

    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….

    1. suraj says:

      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.

      1. Hari says:

        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

  113. Naga says:

    The synchronized block of your code creating multiple objects in multi threaded programming

    1. Naga says:

      Sorry for post my previous info.it’s working fine

  114. MohanV says:

    nice post..everything is discussed here…

  115. Prashant Shahapur says:

    in Singleton Class implements Serilizable, I added readResolve() method but still serialized object and deserialzed objects hashcodes are different…Please confirm me

  116. kush singh says:

    Hi pankaj,
    This is a nice article and almost everything is covered. it help me lot to understand singleton

  117. tadveer Verma says:

    its nice tutorial …………………..

  118. Adyasha Nayak says:

    @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

  119. Nishant Kshirsagar says:

    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

  120. Zaid says:

    Great!!!!!

    1. Kapil Agarwal says:

      I love reading your tutorials. Great explaination !!!!

  121. Shashi says:

    Awesome explanation and very clear thanks a ton to pankaj

  122. Vinodini Vikram says:

    This tutorial gave me good clarity on Singleton Pattern. Thank you.

  123. Priyanka says:

    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.

  124. Akhil says:

    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?

    1. Pankaj says:

      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.

      1. Anuj Agarwal says:

        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();

        1. Jeegar Kumar says:

          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.

  125. micheal says:

    Thanks for your wonderful article

  126. Pavan says:

    Hi Pankaj,

    it is very nice post….one of the best among all intenet post on singleton

  127. RAJ9992 says:

    Really Nice that Sharing your Knowledge to e-learners

  128. Amasa says:

    Very nice post…It was vry helpfull

  129. Sumedh says:

    Awesome post Pankaj…..This post is really very helpful…..Thank you

  130. Neha says:

    All the articles are very supporting. thanks

  131. Jim Halvorsen says:

    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.

  132. Likhit says:

    Awesome Work buddy !!!

  133. Velmurugan A says:

    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….

    1. Pankaj says:

      Yes Reflection will break Bill Pugh implementation by making constructor accessible.

      1. Velmurugan A says:

        thanks…

      2. Velmurugan A says:

        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

        1. Vikram says:

          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.

          1. Velmurugan A says:

            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

        2. Valerio P says:

          Hello, i copy/paste your code in my Eclipse. It works good and no IllegalArgumentException was launched

  134. Prabhavathi says:

    Can you please explain the Singleton enum prevents lazy loading ?I feel that the instance creation happens lazily when it is first accessed.

    1. Pankaj says:

      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.

      1. Durga says:

        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.

  135. Mohan says:

    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,….

  136. Rajesh says:

    Very nice, explained in simple terms.

  137. DHARMENDRA KUMAR SAHU says:

    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.

  138. Anshul Jain says:

    This is a nice article and almost everything is covered. Thanks a ton.

  139. Prakash says:

    Very good site for design patterns. Explanation is easy and up to the mark. Thanks.

  140. H Singh says:

    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

    1. Pankaj says:

      Yes we can and thats why we can have readResolve() method implementation to get the same instance.

      1. H Singh says:

        What is the purpose of readResolve() method? how it helps in maintaining only one object of singleton class.

      2. Taufique Alam says:

        can you tell in which class we can find viewResolve().

  141. Vishnu says:

    This web site useful for me, Thanks a ton.

  142. Vishnu says:

    Sir,

    As per u provide contains which one is the best practices for the Singleton Pattern.

    Regards
    Vishnu

    1. Pankaj says:

      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.

      1. Vikki says:

        But you’d written that enum Singleton is not lazy loaded. So can you say enum singleton is lazy or not?

  143. Tarun Soni says:

    nice tutorial thanks …..

    i have one question fro you
    How annotations works internally?

  144. erick says:

    Very nice post:-) keep up the good work

  145. poonam says:

    owesome post…evrything is discussed about singleton.keep it up….nd thanks

    1. Pankaj says:

      Thanks Poonam, glad you liked it.

      1. rajendra says:

        what is difference between singleton and static method

        1. Tejas says:

          singleton is a design pattern and static is a key word in JAVA

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages