Singleton Design Pattern in Java

Learn how Java Singleton works with enum and holder implementations, runnable code, thread-safety limits, serialization, and practical alternatives.

Two clients request one shared Singleton instance per loaded class.

The Singleton pattern ensures that a class has one instance and gives other classes a way to access it. A dependent class uses that access point instead of creating a separate instance with new. Every caller receives the same instance.

In a regular Java class, the access point is usually a static method. The class can create the instance when that method is first called, and the method then returns the same instance on later calls. An enum singleton provides its one named constant as the access point instead.

“Ensure a class only has one instance, and provide a global point of access to it.”

1. How the Singleton Pattern Works

The Singleton is the class or enum that holds the shared instance. Its access point is the method or named constant through which other classes obtain that instance.

ParticipantResponsibility
SingletonControls how its one instance is created.
getInstance() or INSTANCEGives callers a reference to that instance.
ClientRequests the shared instance and calls its methods.

Two clients use the access point and receive references to the same instance. Neither client creates its own instance through a public constructor. The diagram shows both references leading to one instance; it does not imply that either client owns it.

Two clients obtain the same instance from a singleton access point

The instance is shared within the scope of one loaded class. A class loader is the JVM component that loads class definitions. A second class loader can load another copy of the class, and another JVM process has its own classes and objects. A Singleton therefore cannot coordinate state across application servers by itself.

2. Singleton Pattern in Action

Imagine a checkout application that assigns a number to each new order. Two checkout requests in the same running application must use one sequence: the first order receives number 1, and the next receives number 2. If each request creates its own generator, both could issue number 1. This example keeps the sequence in one shared generator so both requests advance the same counter.

We will implement that generator in two ways. OrderNumberGenerator is an enum singleton. LazyOrderNumberGenerator is a regular class whose instance is created on first access. SingletonDemo simulates two checkout requests by obtaining the generator twice, then calling nextNumber() through each reference. It also compares the references to show whether they lead to the same instance. These are alternative implementations, so each starts its own sequence at 1.

Pattern participantExample typeWhat it does
SingletonOrderNumberGenerator or LazyOrderNumberGeneratorHolds the counter and assigns the next number.
Access pointOrderNumberGenerator.INSTANCE or LazyOrderNumberGenerator.getInstance()Gives each request the shared generator for that scenario.
ClientSingletonDemoRepresents two requests, compares their references, and prints the numbers they receive.

In either scenario, the two requests should receive the same generator instance. Calls to nextNumber() should then return 1 and 2 because the calls advance one shared counter. The example uses an AtomicInteger, a JDK counter that can be incremented safely when multiple threads call it. The numbers are local to this JVM and reset when the application restarts; they are not suitable as durable order IDs across servers.

Two checkout requests obtain one shared order number generator in each implementation

3. Singleton Pattern Implementation

The enum has one declared constant, its named value INSTANCE. Java controls creation of enum constants, so callers cannot construct another OrderNumberGenerator with new. The generator keeps its next number in an AtomicInteger. Each call to incrementAndGet() increments that counter and returns the new value.

import java.util.concurrent.atomic.AtomicInteger;

public enum OrderNumberGenerator {
    INSTANCE;

    private final AtomicInteger next = new AtomicInteger();

    public int nextNumber() {
        return next.incrementAndGet();
    }
}

The other implementation is a regular class. Its private constructor prevents ordinary callers from constructing it. The nested Holder stores the shared instance in a static field. Java initializes that nested class when getInstance() first reads Holder.INSTANCE, so the instance is created on the first request. It has its own AtomicInteger; its sequence is separate from the enum sequence.

import java.util.concurrent.atomic.AtomicInteger;

public final class LazyOrderNumberGenerator {
    private final AtomicInteger next = new AtomicInteger();

    private LazyOrderNumberGenerator() {
    }

    private static class Holder {
        private static final LazyOrderNumberGenerator INSTANCE = new LazyOrderNumberGenerator();
    }

    public static LazyOrderNumberGenerator getInstance() {
        return Holder.INSTANCE;
    }

    public int nextNumber() {
        return next.incrementAndGet();
    }
}

Java lets one thread initialize the holder class while other threads wait for that initialization to finish. This gives every caller the same fully constructed instance without adding a lock or volatile field to getInstance(). The Java Language Specification on class initialization describes that coordination. The code excerpts omit package declarations; the complete source directory is linked below.

4. Demo

The demo runs the two implementations separately. For each one, it obtains the generator twice, checks whether both references identify the same instance, and requests two order numbers. The first call should return 1, and the second should return 2.

public class SingletonDemo {
    public static void main(String[] args) {
        OrderNumberGenerator first = OrderNumberGenerator.INSTANCE;
        OrderNumberGenerator second = OrderNumberGenerator.INSTANCE;
        System.out.println("enum same instance: " + (first == second));
        System.out.println("enum order numbers: " + first.nextNumber() + ", " + second.nextNumber());

        LazyOrderNumberGenerator lazyFirst = LazyOrderNumberGenerator.getInstance();
        LazyOrderNumberGenerator lazySecond = LazyOrderNumberGenerator.getInstance();
        System.out.println("holder same instance: " + (lazyFirst == lazySecond));
        System.out.println("holder order numbers: " + lazyFirst.nextNumber() + ", " + lazySecond.nextNumber());
    }
}

From the root of a clone of the source repository, compile the three files and run SingletonDemo:

javac -d out src/main/java/com/howtodoinjava/patterns/creational/singleton/*.java
java -cp out com.howtodoinjava.patterns.creational.singleton.SingletonDemo
enum same instance: true
enum order numbers: 1, 2
holder same instance: true
holder order numbers: 1, 2

4.1. enum Scenario

The first comparison prints true because both variables refer to OrderNumberGenerator.INSTANCE. The first call to nextNumber() increments its counter from 0 to 1. The second call uses the same instance, so it advances that counter to 2.

4.2. Holder Scenario

The holder scenario also prints true. The first call to LazyOrderNumberGenerator.getInstance() initializes the holder and creates the generator. The second call returns that existing instance, so its two calls to nextNumber() print 1 and 2. Each scenario has a separate counter, which is why both begin at 1.

The shared instance explains why the sequence continues across the two references. AtomicInteger makes each increment safe if two threads call nextNumber() concurrently. The output does not prove durability across restarts or uniqueness across JVM processes.

5. Similar Patterns and When to Use Them

The Factory pattern centralizes the choice of which object to create. Singleton instead controls how many instances of one type are available. A factory could return a singleton, but a factory does not require a single shared instance.

The two implementations above differ in when Java creates their instances. Java creates the enum constant when it initializes the enum class. The holder approach waits until the first call to getInstance() accesses the nested Holder class. Both approaches give callers one shared instance of their respective type.

ApproachInstance creationGood fit
One enum constantWhen the enum class initializes.A compact singleton whose type can be an enum.
Initialization holderWhen getInstance() first reads the holder field.A regular class that needs lazy creation.
Eager static fieldWhen its class initializes.A regular class that is always used and cheap to create.
Synchronized accessorOn the first call to a synchronized method.A simple lazy class when locking on every access is acceptable.
Double checked lockingOn the first call, using a lock and a volatile field.A specialized lazy class when its extra code is justified.
Application supplied shared instanceDuring application setup.Code that should receive its dependency explicitly, especially in tests.

There are other ways to make a regular class lazy, but they need care when more than one thread can call the accessor. A plain if (instance == null) check can let two threads see an empty field and each create an instance. A synchronized accessor prevents that by allowing one thread through the method at a time, although every access takes the lock.

Double checked locking avoids taking that lock after the instance exists. The first check happens before locking; if the field is empty, the thread takes the lock and checks again. The second check matters because another thread may have created the instance while this one waited. The field must be volatile so other threads see the fully constructed instance. For this example, the enum and holder implementations achieve the goal with less code.

Safe instance creation does not make mutable methods thread-safe. The order number counter is why this example uses AtomicInteger. If it used a plain integer field, two threads could read the same value before either writes the next one. Both requests might then receive the same number. When clients need a replaceable generator in tests, passing it through constructors can be clearer than letting every client call a global accessor.

6. FAQs

6.1. Does serialization create another enum instance?

No. Java serializes an enum constant by name and resolves it to the existing constant during deserialization. This does not serialize the constant’s mutable fields. The serialization specification describes the special handling.

6.2. Should a singleton declare a serialVersionUID?

A regular singleton class needs to consider serialVersionUID only if it implements Serializable. The ID helps Java check whether the class version matches serialized data. It does not tell Java to return the existing singleton instance when that data is read back.

A serializable class can define readResolve() to return its existing instance after deserialization. Our LazyOrderNumberGenerator does not implement Serializable, so it needs neither mechanism. An enum uses special serialization rules and ignores a declared serialVersionUID. The Serializable contract explains the version check.

6.3. Can reflection create another instance?

Ordinary reflective construction of enum constants is prohibited. A private constructor in a regular class is less absolute because privileged mechanisms may bypass normal access. The enum language rules explain the enum restriction.

6.4. Is there only one instance in the entire application deployment?

No. Separate class loaders or JVM processes can each have an instance. If multiple processes must agree on one setting or resource, they need an appropriate shared external system.

6.5. Is there a singleton in the JDK?

Yes. The Runtime class has one instance for the current Java application, accessed through Runtime.getRuntime(). It is a concrete example of a shared access point, but it does not change the scope limits described above.

7. Conclusion

Singleton gives callers one shared instance within a loaded class. An enum is a compact choice when the singleton can be an enum; a holder suits a regular class that should create its instance on first access. If the instance has changing data, its methods still need their own concurrency rules. Separate class loaders and JVM processes do not share the same instance.

Happy Learning!

Source Code on Github

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

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

  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

  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

  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

  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.

  6. very helpful, thanks for clearing all the doubts of singleton pattern, have never seen such a good blog.

    thanks once again

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

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

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

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

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

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

  11. In final example, why dont you declare variable as volatile. How your final solution will work in multithreaded enviornment

  12. Hi lokesh ,
    can you plese explain why you are going to synchronize the object in lazy initialization case

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

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

      • 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) “

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

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

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

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

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

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

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

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

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

  20. They sequentially goes to synchronized block and create the instance.

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

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

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

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

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

    Thanks again LOKESH.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    private BillPughSingleton() {

    }
    .

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

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

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

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

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

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

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

        • 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”.

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

  36. Hello, I found that in case the constructor is declared to throw an exception, the solution Bill pugh can not be used.

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

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

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

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

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

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

    • I doubt because i have not implemented Cloneable interface either. But agree, a clone methos which throws CloneNotSupportedException will be a good addition.

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

Comments are closed.

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.