Java Singleton Pattern: Class Design with Examples

Singleton pattern enables an application to create the one and only one instance of a Java class per JVM, in all possible scenarios.

The singleton pattern has been debated long enough in the Java community regarding possible approaches to make any class singleton. Still, you will find people not satisfied with any solution you give. They cannot be overruled either. In this post, we will discuss some good approaches and will work towards our best possible effort.

Singleton term is derived from its mathematical counterpart. Singleton pattern helps to create only one instance per context. In Java, one instance per JVM.

Let’s see the possible solutions to create singleton objects in Java.

1. Singleton using Eager Initialization

This is a solution where an instance of a class is created much before it is actually required. Mostly it is done on system startup.

In an eager initialization singleton pattern, the singleton instance is created irrespective of whether any other class actually asked for its instance or not. This is done usually using a static variable as these get initialized at the application startup, always.

public class EagerSingleton {

	private static volatile EagerSingleton instance = new EagerSingleton();

	// private constructor
	private EagerSingleton() {
	}

	public static EagerSingleton getInstance() {
	return instance;
	}
}

The above method works fine, but it has one drawback. The instance is created irrespective of it is required in runtime or not. If the instance is not a big object and you can live with it being unused, this is the best approach.

Let’s solve the above problem in the next method.

2. Singleton using Lazy Initialization

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process, until the first time it is needed.

In the context of the singleton pattern, lazy initialization restricts the creation of the instance until it is requested for first time.

Lets see this in code:

public final class LazySingleton {

	private static volatile LazySingleton instance = null;

	// private constructor
	private LazySingleton() {
	}

	public static LazySingleton getInstance() {
		if (instance == null) {
			synchronized (LazySingleton.class) {
				instance = new LazySingleton();
			}
		}
		return instance;
	}
}

On the first invocation, the getInstance() method will check if the instance is already created using the instance variable. If there is no instance i.e. the instance is null, it will create an instance and will return its reference. If the instance is already created, it will simply return the reference of the instance.

But, this method also has its own drawbacks. Let’s see how.

Suppose there are two threads T1 and T2. Both come to create the instance and check if “instance==null”. Now both threads have identified instance variable as null thus they both assume they must create an instance. They sequentially go into a synchronized block and create the instances. In the end, we have two instances in our application.

This error can be solved using double-checked locking. This principle tells us to recheck the instance variable again in a synchronized block as given below:

public class LazySingleton {

	private static volatile LazySingleton instance = null;

	// private constructor
	private LazySingleton() {
	}

	public static LazySingleton getInstance() {
		if (instance == null) {
			synchronized (LazySingleton.class) {
				// Double check
				if (instance == null) {
					instance = new LazySingleton();
				}
			}
		}
		return instance;
	}
}

Above code is the correct implementation of the singleton pattern.

Please be sure to use “volatile” keyword with instance variable otherwise you can run into an out of order write error scenario, where reference of an instance is returned before actually the object is constructed i.e. JVM has only allocated the memory and constructor code is still not executed.

In this case, your other thread, which refers to the uninitialized object may throw NullPointerException and can even crash the whole application.

3. Singleton with Bill Pugh Solution

Bill Pugh was the main force behind the Java memory model changes. His principle “Initialization-on-demand holder idiom” also uses the static block idea, but in a different way. It suggests using a static inner class.

public class BillPughSingleton {

	private BillPughSingleton() {
	}

	private static class LazyHolder {
		private static final BillPughSingleton INSTANCE = new BillPughSingleton();
	}

	public static BillPughSingleton getInstance() {
		return LazyHolder.INSTANCE;
	}
}

As you can see, until we need an instance, the LazyHolder class will not be initialized until required and you can still use other static members of BillPughSingleton class.

This is the solution, i will recommend to use. I have used it in my all projects.

4. Singleton using Enum

This type of implementation employs the use of enum. Enum, as written in the Java docs, provided implicit support for thread safety and only one instance is guaranteed. Java enum singleton is also a good way to have singleton with minimal effort.

public enum EnumSingleton {

	INSTANCE;

	public void someMethod(String param) {
		// some class member
	}
}


5. Best Practice: Add readResolve() to Singleton Instance

By now you must have made your decision about how you would like to implement your singleton. Now let’s see other problems that may arise even in job interviews.

Let’s say your application is distributed and it frequently serializes objects into the file system, only to read them later when required. Please note that de-serialization always creates a new instance.

Let’s understand using an example:

Our singleton class is:

public class DemoSingleton implements Serializable {

	private volatile static DemoSingleton instance = null;

	public static DemoSingleton getInstance() {
		if (instance == null) {
			instance = new DemoSingleton();
		}
		return instance;
	}

	private int i = 10;

	public int getI() {
		return i;
	}

	public void setI(int i) {
		this.i = i;
	}
}

Let’s serialize this class and de-serialize it after making some changes:

public class SerializationTest {

	static DemoSingleton instanceOne = DemoSingleton.getInstance();

	public static void main(String[] args) {
		try {
			// Serialize to a file
			ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
			out.writeObject(instanceOne);
			out.close();

			instanceOne.setI(20);

			// Serialize to a file
			ObjectInput in = new ObjectInputStream(new FileInputStream("filename.ser"));
			DemoSingleton instanceTwo = (DemoSingleton) in.readObject();
			in.close();

			System.out.println(instanceOne.getI());
			System.out.println(instanceTwo.getI());

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

The program output:

20
10

Unfortunately, both variables have different values of the variable “i”. Clearly, there are two instances of our class. So, again we are in the same problem of multiple instances in our application.

To solve this issue, we need to include a readResolve() method in our DemoSingleton class. This method will be invoked when you de-serialize the object. Inside of this method, you must return the existing instance to ensure a single instance application-wide.

public class DemoSingleton implements Serializable {

	private volatile static DemoSingleton instance = null;

	public static DemoSingleton getInstance() {
		if (instance == null) {
			instance = new DemoSingleton();
		}
		return instance;
	}

	protected Object readResolve() {
		return instance;
	}

	private int i = 10;

	public int getI() {
		return i;
	}

	public void setI(int i) {
		this.i = i;
	}
}

Now when you execute the class SerializationTest, it will give you the correct output.

20
20

6. Best Practice: Add SerialVersionUId to Singleton Instance

So far so good. Until now, we have solved both of the problems of synchronization and serialization. Now, we are just one step away from a correct and complete implementation. The only missing part is a serial version ID.

This is required in cases where your class structure changes between serialization and deserialization. A changed class structure will cause the JVM to give an exception in the de-serializing process.

java.io.InvalidClassException: singleton.DemoSingleton; local class incompatible: stream classdesc serialVersionUID = 5026910492258526905, local class serialVersionUID = 3597984220566440782
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at singleton.SerializationTest.main(SerializationTest.java:24)

This problem can be solved only by adding a unique serial version ID to the class. It will prevent the compiler from throwing the exception by telling it that both classes are the same, and will load the available instance variables only.

7. Singleton Pattern Examples in JDK Classes

I just thought to add some examples that can be referred to for further study and mentioned in interviews.

  • java.awt.Desktop#getDesktop()
  • java.lang.Runtime#getRuntime()
  • Logger Instances: Many logging frameworks, like Log4j or SLF4J, often implement Singleton patterns for their logger instances to ensure that all parts of the application use the same logger configuration and instance.
  • Java Naming and Directory Interface (JNDI): In Java EE applications, the InitialContext class from the javax.naming package is often implemented as a Singleton. It provides access to the naming and directory services for JNDI.

8. Conclusion

After having discussed so many possible approaches and other possible error cases, I will recommend to you the code template below, to design your singleton class which shall ensure only one instance of a class in the whole application in all the above-discussed scenarios.

public class DemoSingleton implements Serializable {

	private static final long serialVersionUID = 1L;

	private DemoSingleton() {
		// private constructor
	}

	private static class DemoSingletonHolder {
		public static final DemoSingleton INSTANCE = new DemoSingleton();
	}

	public static DemoSingleton getInstance() {
		return DemoSingletonHolder.INSTANCE;
	}

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

I hope this post has enough information to help you understand the most common approaches for the singleton pattern and singleton best practices. Let me know your thoughts.

Happy Learning !!

Leave a Comment

  1. Thank you for this great article! I’m developing an QA automation framework and I read user credentials using property file but in the future, this will be executed using a jenkins job which enables parallel execution to execute test cases faster. So when using jenkins parallel execution, how can we make sure I load this property file once?

    Thank you

    Reply
    • Sorry, I do not understand your question properly, partly because I am not aware of what exactly happen during parallel execution in Jenkins. Perhaps, if you can rephrase your question without Jenkins, I can help.

      Leaving for others to comment, if they can help.

      Reply
  2. Hi Lokesh,
    I would want to know the practical usage of readResolve() method. When i serialize an object , while deserializing i expect to get the content that was serialized. With the ReadResolve() method, if i return the existing singleton instance i end up returning the existing instance and i will not get the values that were actually serialized.
    I am not able to get the intent of ReadResolve() method

    Reply
  3. Will the Bill Pugh solution work in case of multiple threads? As mentioned in the Drawback of singleton with Lazy case.
    What will happen if multiple threads try to get the instance of the singleton class

    Reply
  4. Hello Lokesh,

    Why your recommended versions, removed the line
    private volatile static DemoSingleton instance = null;

    I am confused, you introduced it and then removed in your two recommended versions. why?

    Regards,

    Ram Srinivasan

    Reply
  5. Hi Lokesh,
    I was asked in an Interview that you are creating private constructor so that you can not access the class from outside, then why we are declaring the object refernce variable(private static volatile EagerSingleton instance) as private.

    Reply
  6. I understood that deserialization creates another instance of Singleton. But Why ? does it calls private constructor internally ?
    On what instance does readResolve method is invoked when the deserialized instance is a different instance altogether ?

    Reply
  7.  
    public class BillPughSingleton {
        private BillPughSingleton() {
        }
     
        private static class LazyHolder {
            private static final BillPughSingleton INSTANCE = new BillPughSingleton();
        }
     
        public static BillPughSingleton getInstance() {
            return LazyHolder.INSTANCE;
        }
    }
    

    As per you recommend above code template to design singleton class.
    But how Thread safety achieve in above code ??

    Reply
    • It’s already threadsafe because java static field/class initialization is thread safe – at JVM level. Static initialization is performed once per class-loader and JVM ensures the single copy of static fields. So even if two threads access above code, only one instance of class will be created by JVM.

      Reply
  8. Hi Lokesh ! I have read your warning to use volatile keyword but i can’t understand it properly. Will you please elaborate it and explain it with any example ?

    Reply
  9. Hi Lokesh sir,
    Nice post i am very good clearity abouth Singleton class but i am confused readResolve() method please explain me which class declare the readResolve() method and who will call?

    Reply
    • Hi Lokesh,
      I am leave here my singleton code please say me is all angle correct or not…
      package com.sampat.stp;

      import java.io.Serializable;

      import com.sampat.commans.ComminsUtils;

      public class PrinterUtil extends ComminsUtils {

      /**
      *
      */
      private static final long serialVersionUID = 1L;
      // create an object of PrinterUtil
      // private static PrinterUtil instance=new PrinterUtil();
      private static boolean isInstantiated = false;
      private static PrinterUtil instance;

      /*
      * static{ instance=new PrinterUtil(); }
      */

      // make the constructor private so that this class cannot be
      // instantiated
      private PrinterUtil() throws InstantiationException {

      if (isInstantiated == true) {
      throw new InstantiationException();
      } else {
      isInstantiated = true;
      }
      System.out.println(“PrintUtil:0-param constructor”);
      // no task
      }

      // Get the only object available
      public static PrinterUtil getInstance() throws InstantiationException {
      if (instance == null) {
      synchronized (PrinterUtil.class) {
      // Double Check
      if (instance == null) {
      try {
      Thread.sleep(1000);
      } catch (Exception e) {
      e.printStackTrace();
      }

      instance = new PrinterUtil();
      }
      }
      }
      return instance;
      }

      // Instead of the object we’re on, return the class variable singleton
      public Object readResolve() {
      return instance;
      }

      @Override
      public Object clone() throws CloneNotSupportedException {

      return new CloneNotSupportedException();
      }
      }

      Reply
  10. Hi

    Every thing you have written in this post is excellent .
    I have some doubts. Please clarify it.

    Singleton means only one instance of class with in a jvm. There is two web application wants to use same singletone class.But whenever , web application uses this singleton class it creates one instance for an application means per application one instnace .But my web application runs under jvm with same server

    Reply
  11. Hi Lokesh,
    Thanks for the nice explanation. I have one query- how can we ensure or use singelton behaviour in clustered environment?

    Reply
      • hi Lokesh,
        Thanks for giving such a good content, but I think in definition of Singleton there is little correction so it will become perfect “one instance per Java Virtual Machine”

        according to me

        “one instance of a class is created within hierarchy of ClassLoader or (within the scope of same application) “

        Reply
      • I could not understand why you went further than the “Bill pugh solution” is it because “Bill pugh solution” is wrong or you wanted to show alternative to “Bill pugh solution”?

        Reply
  12. I was asked in an interview to Create singleton class using public constructor. is it possible?if yes, could you please provide the details

    Reply
    • Hi Madhav , yes it is possible. please go through following code

      public class Singleton {

      private static Singleton instance;
      public static synchronized Singleton getInstance() {
      return (instance != null) ? instance : new Singleton();
      }
      public Singleton() {
      System.out.println(“in constructor”);
      synchronized (Singleton.class) {
      if (instance != null) {
      throw new IllegalStateException();
      }
      instance = this;
      }
      }
      }

      Reply
  13. Hi Lokesh, Thanks for info and i have small doubt weather “Bill pugh solution” is Lazy loading or Eager loading. Thanks in advance

    Reply
  14. Instead of double checking, why not move the if(instance == null) check in the synchronized block itself – so that only one thread enters, checks and decides to initialize. Please share your thoughts. Thanks.

    Reply
    • You made valid argument. It will definitely cut-down at least 2-3 lines of code needed to initialize the object. BUT, when application is running and there are N threads which want to check if object is null or not; then N-1 will be blocked because null check is in synchronized block. If we write logic as in double checking then there will not be any locking for “ONLY” checking the instance equal to null and all N threads can do it concurrently.

      Reply
      • I had the same idea about moving the if inside the synchronized block. It never dawned on me that this would cause extra locking every time someone asked for the instance. Very good explanation as to why using the double check is much better.

        Reply
  15. Hi Lokesh,
    I have read a number of articles on Singleton But after reading this,I think i can confidently say in an interview that I am comfortable with this TOPIC.And also love the active participation of everyone which leads to some nice CONCLUSIONS.

    Reply
  16. Hi Lokesh,
    Your way of converting difficult topic to easier is remarkable. Apart from Gang Of Four Design Patterns, if you can take time out in explaining J2EE Design patterns also then that will be really great.

    Reply
  17. They sequentially goes to synchronized block and create the instance.

    In the above line the word “Synchronized” has to be modified as “static”

    Reply
  18. Hi Lokesh Sir, i am new in java and tryning to make a slideshow in my project.can you please help me what i can do.I have 2 option 1st using JavaScript and 2nd using widget.which are best for any website?

    Reply
  19. Great article, thanks! BTW, is it a good idea to use the singleton for a configuration object which can be changed after creation?
    Thanks!

    Reply
  20. Hello Lokesh,
    Very nice and informative article.

    There is one typo that I have observed.
    While explaining double-checked locking , you are referring to class name as EagerSingleton but it is lazy singleton.
    I would be more clear if you make the name LazySingleton.

    Thanks this is just a suggestion to make this excellent article a bit better.

    Thanks Taufique Shaikh.

    Reply
  21. Nice article… i was looking for this concept with multiple doubts. My all doubts are cleared by reading all these comments.

    Thanks again LOKESH.

    Reply
  22. Lokesh I would love to understand why you favor the Bill pugh’s solution over the Enum solution?

    The enum appears to solve synchronization, serialization, and serial version id issues.

    Reply
    • 1) enums do not support lazy loading. Bill pugh solution does.
      2) Though it’s very very rare but if you changed your mind and now want to convert your singleton to multiton, enum would not allow this.

      If above both cases are no problem for anybody, the enum is better.

      Anyway, java enums are converted to classes only with additional methods e.g. values() valueOf()… etc.

      Reply
  23. Hi Lokesh,
    Thanks for writing such a good informative blog. But i had one doubt on singleton. As per my understanding singleton is “Single instance of class per JVM ” . But when application is running production clustered environment with multiple instances of JVM running can break the singleton behavior of the class? i am not sure if does that make any sense or not but question stricked in my mind an thought of clearing it.

    Amit

    Reply
    • You are right.. In clustered deployment, there exist multiple instances of singleton. You are right, singleton is one per JVM. That’s why never use singleton to store runtime data. Use it for storing global static data.

      Reply
  24. One major drawback of the singletons presented here (as well as enums in general) is however that they can never be garbage collected which further leads to the classloader which loaded them (and all of the classes it loaded) can never be unloaded and therefore will raise a memory leak. While for small applications this does not matter that much, for larger applications with plugin-support or hot-deployment feature this is a major issue as the application container has to be restarted regularly!

    While “old-style” singletons offer a simple workaround on using a WeakSingleton pattern (see the code below) enums still have this flaw. A WeakSingleton simply is created like this:

    public class WeakSingleton
    {
    private static WeakReference REFERENCE;

    private WeakSingleton()
    {

    }

    public final static WeakSingleton getInstance()
    {
    if (REFERENCE == null)
    {
    synchronized(WeakReference.class)
    {
    if (REFERENCE == null)
    {
    WeakSingleton instance = new WeakSingleton();
    REFERENCE = new WeakReference(instance);
    return instance;
    }
    }
    }
    WeakSingleton instance = REFERENCE.get();
    if (instance != null)
    return instance;

    synchronized(WeakSingleton.class)
    {
    WeakSingleton instance = new WeakSingleton();
    REFERENCE = new WeakReference(instance);
    return instance;
    }
    }
    }

    It bahaves actually like a real singleton. If however no strong reference is pointing at the WeakSingleton it gets eligible for garbage collection – so it may get destroyed and therefore lose any state. If at least one class is keeping a strong reference to the weak singleton it wont get unloaded. This way it is possible to provide singleton support in large application containers and take care of perm-gen out of memory exceptions on un/reloading multiple applications at runtime.

    However if the weak singleton is used wrongly, it may lead to surprises:

    // some code here. Assume WeakSingleton was not invoked before so no other object has a reference to the singleton

    {
    WeakSingleton someManager = WeakSingleton.getInstance();
    manager.setSomeStateValue(new StateValue());

    StateValue value = manager.getValue(); // safe operation

    }

    // outside of the block – assume garbage collection hit just the millisecond before
    StateValue value = manager.getValue(); // might be null, might be the value set before, might be a default value

    As mentioned before enum singletons don’t provide such a mechanism and therefore will prevent the GC from collecting enums ever. Java internally converts enums to classes and adds a couple of methods like name(), ordinal(), … Basically an enum like:

    public enum Gender
    {
    FEMALE,
    MALE;
    }

    will be converted to

    public class Gender
    {
    public final static Gender FEMALE = new Gender();
    public final static Gender MALE = new Gender();

    ….
    }

    As on declaring Gender.FEMALE somewhere a strong reference will be created for FEMALE that points to itself and therefore will prevent the enum from being garbage collected ever. The workarround with WeakReferences is not possible in that case. The only way currently possible is to set the instances via reflection to null (see . If this enum singleton is however shared among a couple of applications nulling out the instance will with certainty lead to a NullPointerException somewhere else.

    As enums prevent the classloader which loaded the enum from being garbage collected and therefore prevent the cleanup of space occupied by all the classes it loaded, it leads to memory leaks and nightmares for application container developerand app-developer who have to use these containers to run their business’ apps.

    Reply
    • Thanks for your comment here. This is real value addition to this post.
      Yes, I agree that singleton are hard to garbage collect, but frameworks (e.g. Spring) have used them as default scope for a reason and benefits they provide.
      Regarding weak references, i agree with your analysis.

      Reply
      • small correction of the WeakSingleton code above as it was already late yesterday when I wrote the post: The class within the first synchronized(…) statemend should be WeakSingleton.class not WeakReference.class. Moreover, the comment-software removed the generic-syntax-tokens (which the compiler is doing too internally but additionally adds a cast for each generic call instead) – so either a generic type has to be added to the WeakReference of type WeakSingleton or a cast on REFERENCE.get() to actually return a WeakSingleton instead of an Object.

        Moreover, the transformation code for the enum into class is not 100% exact and therefore correct – so don’t quote me on that. It was just a simplification to explain why enums create a memory leak.

        Reply
  25. Hi Lokesh,

    It seems like the this can be broken using reflexion API as well.
    is the static inner class will be loaded at first call? or at class load time?

    Reply
      • Thanks Lokesh .But we can use static inner class variable and mark as null using reflexion.
        Is any way to save the private variable from reflxion???

        Reply
          • in order to block Reflection you just need to throw IllegalStateException from the private constructor.

            Like this :
            private Singleton() {
            // Check if we already have an instance
            if (INSTANCE != null) {
            throw new IllegalStateException(“Singleton” +
            ” instance already created.”);
            }
            System.out.println(“Singleton Constructor Running…”);
            }

          • Hi Lokesh,

            You can actually change the values of private variables using reflection API. This can be done using getDeclaredField(String name) and getDeclaredFields() methods in Class class. This way you can get the an object of the field and then you can call the set(Object obj, Object value) method on the Field object to change it’s value. For Singleton classes, the private constructor should always be written as follow:

            private Singleton()
            {
            if (DemoSingletonHolder.INSTANCE != null)
            {
            throw new IllegalStateException(“Cannot create second instance of this class”);
            }
            }

  26. Thanks for the article.

    Making EagerSingleton instance volatile does not have any significance. As it is a static variable, it will be initialized only once when class is loaded. Thus, it will always be safely published. Agree?

    Reply
  27. Lokesh, Many thanks for sharing the wonderful information….I have got one problem in my mind from my product only. We have helperclasse for almost entire the functionality ad we create single ton instance of each class.Now suppose I have a helperclass CustomeHelper and there Is method called createCustomer(). Singleton instance of this class is present. Now this is very important class of my application. And access by so may teller from banks…..Than if I will get the second request than It would not be process because my class is single ton…1st thread is using the instance of singleton class…..Could you pls share your point….

    Reply
    • Singleton means only one instance of class. It does not add any other specific behavior implicitly, So createCustomer() will be synchronized only if you declare it to be, not because CustomeHelper class is singleton.
      Regarding your request would be blocked, this depends on cost of synchronization. If cost is not much, the you can do it without any problem. This happens all the time at DAO layer.

      Reply
  28. Hi Lokesh , nice post , i need some explanation for this

    private BillPughSingleton() {

    }
    .

    why you need this private constructor in 4th methof BillPughSingleton ??

    Reply
  29. why we need this readResolve() method and how it will solve the issue, is not clear.

    Can u please explain how it is resolving the issue of more than one instances of singleton class.

    Reply
  30. Yes, Lokesh is right. Actually clone method will not work if you don’t implement Clonable interface. I hope it will through clone not supported exception.

    Reply
  31. Hi Lokesh,

    Very good post…

    I have a doubt – is it possible to generate a duplicate object of a singleton class, using serialization?

    Can u plz provide some ideas that how to make sure to make singleton class more safe.

    Thanks in advance.

    Reply
  32. Hi Lokesh,

    You have done a great job. Every thing you have written in this post is excellent.
    I have some doubts. Please clarify them.

    Can we go for a class with all static methods instead of Singleton? Can we achieve the same functionality like Singleton ?
    Give me some explanation please.

    Reply
    • Both are different things. Singleton means one instance per JVM. Making all methods static does not stop you from creating multiple instances of it. Though all methods are static so they will be present at class level only i.e. single copy. These static methods can be called with/without creating instances of class but actually you are able to create multiple instances and that’s what singleton prevents.

      So in other words, You may achieve/implement the application logic but it is not completely same as singleton.

      Reply
      • Suppose If I make constructor private and write all methods as static. Like almost equal to Math class(final class, private constructor, all static methods), then what will be the difference.

        I am in confusion with these two approaches. When to use what. Pls clarify Lokesh.

        Reply
        • Usually singletons classes are present in form of constant files or configuration files. These classes mostly have a state (data) associated with it, which can not be changed once initialized.

          Math class (or similar classes) acts as singleton, but I prefer to call them “Utility classes”.

          Reply
        • You can actually make use of inheritence and extend parent class in case of Singleton and its not possible if we have final class with all static methods.

          Reply
  33. Hello Lokesh,

    Congratulations for your interesting and informative article.

    Please take a look at the Bill pugh solution, because the method BillPughSingletongetInstance is missing the return type which must be
    BillPughSingleton.

    Keep up the good work…

    Reply
  34. Hi,
    How would you handle a singleton where the constructor can throw an exception?

    To get around the threading issue, I have been using the following:

    private static ClassName inst = null;
    private static Object lock = new Object();

    private ClassName() throws SomeException
    {
    do some operations which may throw exception…
    }

    public static ClassName getInstance() throws Exception
    {
    if (inst == null)
    synchronized (lock)
    if (inst == null)
    inst = new ClassName();
    return inst;
    }

    I want to consider the Bill Pugh method, but without a reliable way of handling exceptions, it’s not really universal.

    Reply
  35. Hi,
    Do you really think in case of Eager Initialization example we need to have a synchronized method and even a null check is required?

    Reply
  36. Hi,
    Do u think in case of eager example we need to have a synchronized method and even this null check is required?
    Because instance would have got initialized at class load itself.

    Reply
  37. What is instance control?

    Instance control basically refers to single instance of the class OR singleton design pattern .

    Java 1.5 onwards we should always prefer ENUM to create singleton instance. It is absolutely safe . JVM guarantees that. All earlier mechanical of controlling instance to single are already broken.

    So in any interview you can confidently say ENUM= provides perfect singleton implementation .

    Now what is readResolve?

    readResolve is nothing but a method provided in serializable class . This method is invoked when serialized object is deserialized. Through readResolve method you can control how instance will be created at the time of deserialization.Lets try to understand some code

    public class President {

    private static final President singlePresident = new President();

    private President(){

    }

    }

    This class generates single instance of President class. singlePresident is static instance and same will be used across.

    But do you see it breaks anywhere?

    Please visit http://efectivejava.blogspot.com/ for more details on this

    Reply
  38. Nice post Lokesh but u have not overridden the clone method because one can create a cloned object which also violates singleton pattern.

    Reply
  39. this is the most complete singleton pattern implementation tutorial I have come across. I got inspired and wrote about it on my blog at Singleton code in Java. Do let me know if I missed anything.
    Thanks

    Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode