Singleton Design Pattern

Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!

A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.

There are only two points in the definition of a singleton design pattern,

  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.

GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]”.

The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton instance.

package com.javapapers.sample.designpattern;
public class Singleton {
	private static Singleton singleInstance;
		private Singleton() {}
	public static Singleton getSingleInstance() {
		if (singleInstance == null) {
			synchronized (Singleton.class) {
				if (singleInstance == null) {
					singleInstance = new Singleton();
				}
			}
		}
		return singleInstance;
	}

You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.

package com.javapapers.sample.designpattern;
public class Singleton {
	private static Singleton singleInstance = new Singleton();
	private Singleton() {}
	public static Singleton getSingleInstance() {
		return singleInstance;
	}
}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

This article is an attempt to explain the basics on singleton design pattern. If you want more insight on singleton refer this technical article “When is a Singleton not a Singleton?” and its references.

Usage of Singleton Pattern in Java API

java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()

This Creational Design Pattern tutorial was added on 02/05/2011.

Comments on "Singleton Design Pattern" Tutorial:

  1. Jigar says:

    +1 for

    synchronized (Singleton.class)

  2. United says:

    Listing 6
    // Double-checked locking — don’t use
    public static MySingleton getInstance() {
    if (_instance==null) {
    synchronized (MySingleton.class) {
    if (_instance==null) {
    _instance = new MySingleton();
    }
    }
    }
    }

    In this situation, we intend to avoid the expense of grabbing the lock of the Singleton class every time the method is called. The lock is grabbed only if the Singleton instance does not exist, and then the existence of the instance is checked again in case another thread passed the first check an instant before the current thread.

  3. United says:

    Which one is better and why?

    public static Singleton getSingleInstance() {
    if (singleInstance == null) {
    synchronized (Singleton.class) {
    if (singleInstance == null) {
    singleInstance = new Singleton();
    }
    }
    }
    return singleInstance;
    }

    OR

    public static synchronized Singleton getSingleInstance() {
    if (singleInstance == null) {
    singleInstance = new Singleton();
    }
    return singleInstance;
    }

  4. United says:

    Unfortunately, double-checked locking causes problems. To wit, compiler optimizations can make the assignment of the new Singleton object before all its fields are initialized. (See “Double-checked locking is broken” in Resources.) The only practical solution is to synchronize the getInstance() method (as in Listing 2).

  5. ludalito says:

    +1

    Singleton was my first pattern too, but I remember it was also my first anti-pattern.
    Beginners often miss the parts about good use, bad use and overuse, and about unit testing as well.

  6. Juned S says:

    Hi first of all would like to say good article..I have few doubts

    1)Isn’t it necessary to use volatile while dealing with threads
    like it should be
    private volatile static Singleton singleInstance;

    2)I still didn’t understand wat is the reason behind checking for instance==null twice?

    It would be of great help if you clear my doubts..

    Regards,
    Juned S

  7. Vishal Patil says:

    Good explanation of singleton design pattern. But even after doing this all, I can still create multiple instances of this class using clone() method from Object class.
    public Object clone() throws CloneNotSupportedException {}
    So one needs to overwrite this method in following way.

    public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
    }

  8. Peter Lawrey says:

    For me the simplest Singlton pattern is

    enum Singleton {
    INSTANCE;
    }

    I wouldn’t use make it more complex unless there is a good reason to do so.

  9. danish says:

    very well explained.
    also plz visit : http://techguru.yakkoo.com
    where i tried to explain it in my own words

  10. Tej says:

    keep sharing the knowledge

  11. Sebastian says:

    Singleton could be sometimes useful.

    Very nice explanation.

  12. Srinivas says:

    Instance can created by using dynamic class loading also .Singleton pattern can fail in that case. see my example in the below
    —————————————————
    Class.forName(“org.sri.design.ptrn.singleton.Singleton”);
    Singleton instance3 = (Singleton)classSingleton.newInstance();

    ——————————————-
    package org.sri.design.ptrn.singleton;

    import org.sri.corejava.basic.Jeep;

    public class Singleton {
    private static Singleton singleInstance;
    private Singleton(){

    }
    public static Singleton getSingleInstance(){
    if(singleInstance == null){
    synchronized(Singleton.class){
    if(singleInstance == null){
    singleInstance = new Singleton();
    }
    }
    }
    return singleInstance;
    }
    public static void main(String args[]){
    Singleton instance1 = Singleton.getSingleInstance();
    System.out.println(“Instance Id=”+instance1.toString());

    Singleton instance2 = Singleton.getSingleInstance();
    System.out.println(“Instance Id=”+instance2.toString());
    //dynamic class loading
    Class classSingleton;
    try {
    classSingleton = Class.forName(“org.sri.design.ptrn.singleton.Singleton”);
    Singleton instance3 = (Singleton)classSingleton.newInstance();
    System.out.println(“Instance Id=”+instance3.toString());

    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    catch(InstantiationException ie){
    ie.printStackTrace();
    }
    catch(IllegalAccessException iae){
    iae.printStackTrace();
    }
    }
    }

  13. Srinivas says:

    To avoid dynamic class loader problem don’t use default constructor
    private Singleton(int arg){

    }

  14. Srinivas says:

    private Singleton(){
    if(singleInstance!= null){
    throw new Error(“Don’t want any more instances”);
    }
    }
    add above code to singleton instance creation to avoid Reflections

  15. Uday Kiran says:

    In the link referenced above it is said not to use synchronized on a block, instead use it on a method –
    “Multiple instances can be created even if you add a synchronized(this) block to the constructor call, as in Listing 4:”. Can you shed more light on this please ?

  16. madhu says:

    Good Tutorial. But I think clonable must be implemented with throwing the clon not supported exception.

  17. ram says:

    gud afnoon sir.
    some people ask for using instance block at the time of class loading we can create object of a particular class so where we want that particular class we can instatiated that particular object by using static block then wt is the necessary to use it…

  18. ReDs says:

    Hey..Joe..

    Ur articles are intrseting..I started reading ur java articles..u r explaining in a simple way such a typical topics..thanks a lot..

  19. Gopal says:

    Joe,

    I think you must override the clone() method in the Singleton class to avoid the cloning..

  20. Dean says:

    According to Josh Bloch, use an enum instead: (like Peter Lawrey said above)

    public enum YourSingleton {
    INSTANCE;

    public void doStuff(String stuff) {
    System.out.println(“Doing ” + stuff);
    }
    }

  21. Ajit says:

    @Dean, This is a java specific solution. Off course there can be different flavours of creating a singleton depending on the programming language you choose. But intention here is to understand the concept well and implement it in your own favourite language without any loophole.

  22. vasu says:

    and also avoid the taking high memory operation ra reduced or not

  23. Anonymous says:

    Thanks joe

  24. Srivathsan says:

    Its really very useful to me. Thanks JOE

  25. shishal says:

    I agree with Peter Lawrey.

  26. Suman says:

    This is very clear to me. Thank you JOE.

  27. arch says:

    How does the Early instantiation takes care of multithreading here? I dont understand. Please help.

  28. Sav says:

    Wouldn’t it be better if static function returning instance would be
    public static singleTon getSingletonIns() {
    synchronized (singleTon.class) {
    if (singletonInstance == null) {
    return new singleTon();
    }
    }
    return singletonInstance;
    }
    as there seems no use of outer comparison.?

  29. Anonymous says:

    Want to add one point “we have to Override the Object clone method to prevent cloning”

    public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
    }

  30. Ved Prakash Mishra says:

    Singleton design pattern is not so much easy to implement, still Joe has made it easier in Definition, and yes singleton is used in those project which are having some concentric Rules for Business and might have access those rules globally as per requirement…ri8???

  31. Anurag Saxena says:

    I really appreciate your efforts in making design patterns express in such simple way. However I have a question on the following code snippet.

    ======================================
    package com.javapapers.sample.designpattern;
    public class Singleton {
      private static Singleton singleInstance;
        private Singleton() {}
      public static Singleton getSingleInstance() {
        if (singleInstance == null) {
          synchronized (Singleton.class) {
            if (singleInstance == null) {
              singleInstance = new Singleton();
            }
          }
        }
        return singleInstance;
      }
    =================================

    I see a vulnerability here. If there is a non static member in this class it will be important to declare singleInstance as volatile. The reason is that without that there could be ordering defect because of which some thread(s) may see the non static member as uninitialized(null) even after they are initialized.

  32. dhanesh says:

    Cloning not hadled

  33. Anonymous says:

    Sometimes we have to modify a class that can’t be modified easily. Perhaps you need the source code and don’t have it (as may be the case with a commercial 3rd party class library). Or maybe any change would require modifying lots of existing subclasses. Design patterns offer ways to modify classes in such circumstances.

    Which design pattern fits the above description

  34. rajesh says:

    some may be use cloning in singleton pattern why?……..

  35. chandra sekhar says:

    nice explnation sir, iwant to know wher it is actually used at real time

  36. chandra sekhar says:

    nice explnation sir, iwant to know wher it is actually used at real time

  37. Ritu says:

    Every single page in this blog is helpful :)

  38. lucky says:

    good one

  39. Anonymous says:

    nice to read

  40. sarita says:

    very much informative ..

  41. Ktsh says:

    How we design Singleton pattern in distributed environment. What stratigies we need to follow

  42. kumar says:

    Hi Joe, I wrote below code.
    My question is shouldn’t compiler throw me an error while i try to instantiate 2nd object (SingletonPattern sp2 = new SingletonPattern();
    ) of SingletonPattern class.
    I thought thats the objective of Singleton Pattern , to create only one instance .

    public final class SingletonPattern {
    private static SingletonPattern _instance;
    private SingletonPattern(){
    }

    public static SingletonPattern getInstance()
    {
    if(_instance ==null)
    {
    _instance = new SingletonPattern();
    System.out.println(“new Instance created.._instance= “+ _instance);
    }
    return _instance;
    }
    public static void main(String args[]){
    SingletonPattern sp1 = new SingletonPattern();
    SingletonPattern sp2 = new SingletonPattern();
    }
    }

  43. Ktsh says:

    Hi Joe,
    How do we design Singleton pattern in distributed environment. What stratigies we need to follow..?

  44. viknesh_mannai says:

    hi joe anna,

    I have a query on what you have mentioned here “Factory design pattern can be used to create the singleton instance.”.

    Actually factory design pattern is that “To create an object from one among the subtype”. Then how will that statement true?

    Could you please explain or correct me if i am wrong?

  45. Rambabu M says:

    What is the necessetity of overriding in the following scenario…
    class Singleton {
    private static Singleton singletonObject;
    private Singleton() {}
    public static synchronized Singleton getSingletonObject() {
    if (singletonObject == null) {
    singletonObject = new Singleton();
    }
    return singletonObject;
    }
    public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
    }
    }
    public class SingletonObjectDemo {
    public static void main(String args[]) {
    Singleton obj = Singleton.getSingletonObject();
    System.out.println(“Singleton object :” + obj);
    }
    }

  46. Rambabu M says:

    Hi Joe,
    The clone() method is protected in Object class. My doubt is If I didn’t override that method in Singleton class[below examle], still my class “Singleton” is singleton as we can’t call write obj.clone() in SingletonObjectDemo class?

    what is the necessity of overriding the clone() method ?

    class Singleton {
    private static Singleton singletonObject;
    private Singleton() {}
    public static synchronized Singleton getSingletonObject() {
    if (singletonObject == null) {
    singletonObject = new Singleton();
    }
    return singletonObject;
    }
    public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
    }
    }
    public class SingletonObjectDemo {
    public static void main(String args[]) {
    Singleton obj = Singleton.getSingletonObject();
    System.out.println(“Singleton object :” + obj);
    }
    }

  47. 123123 says:

    Very god one . thanks a lot

  48. khushboo says:

    but sir by using reflection it can access the private data also by grant the policies of instaler file.

  49. […] is the default scope. Singleton design pattern requires no introduction as it is the easiest of all to understand. In the bean definition if the […]

  50. Szulak says:

    Thank you for this article.

  51. vikas says:

    Gr8 blog……..thanks…:)

  52. Anonymous says:

    hi, its singleton when using check with clone() method, but how can we get same hashCode when run this application many times.

    much obliged to you

    Santosh Srivastava

  53. Anonymous says:

    1st one is better

  54. Danial Carter says:

    we would like to see more real life examples and more comparisons with other design patterns.

    thanks

  55. Ravi Kumar says:

    You cannot create a new instance using classObject.newInstance() method in the above example. You will get IllegalAccessException if you try to do that.

  56. Shashank says:

    Thanks sir,
    For any JAVA doubt i only follow your blogs..

  57. Yogendra says:

    why do you need main method in singleton kumar. remove it.

  58. Anonymous says:

    Nice Article…Thank you for the information.

  59. Davy says:

    Thanks!!

  60. Joe says:

    Welcome Shashank.

  61. joy says:

    “synchronized (Singleton.class) ” is for multiple threading environment i guess.. but i am not able to understand the parameter passed here “Singleton.class”, can you explain joe ?

  62. Anil Kumar Khichar says:

    Hi,

    In the early initialization method you have expained:
    package com.javapapers.sample.designpattern;
    public class Singleton {
    private static Singleton singleInstance = new Singleton();
    private Singleton() {}
    public static Singleton getSingleInstance() {
    return singleInstance;
    }
    }

    But I would suggest just directly define it in the following way:

    package com.javapapers.sample.designpattern;
    public class Singleton {
    public static final Singleton singleInstance = new Singleton();
    private Singleton() {}
    }

    Now if any class want’s to access it, it can be very easily as (static variables can be accessed directly. final ensures it’s security i.e any other class can’t modify it.):
    Singleton.singleInstance

    Do you think if there is anything wrong in my way.

  63. Sriks says:

    Thanks for your time and effort to put on Internet world. I really appreciate your patience on this.

    Could you please explain or write-up on Strategy Design pattern – which is also very important?

  64. Rajesh Ranjan says:

    can i call clone() method in singleton class.
    if i clone then what will happen, can you please explain it.

  65. Rajesh Ranjan says:

    can i call clone() method in singleton class.
    if i call then what will happen, can you please explain it.

  66. Raj Patil says:

    II just got out of an interview. The hiring manager is a a Sr. VP in banking. When I told him how the Spring session factory is a factory pattern and when we instantiate the beans/bean class in IoC container, we have a choice of either flag the bean as singleton/prototype pattern. He was unable to accept it. I gave example of Payment-gateway instance as singleton and he was not convinced. Why some architects think that Singleton does not go together with other patterns?

  67. Milan Kamilya says:

    Thanksss

  68. Rajesh says:

    link given for “When is a Singleton not a Singleton?” is broken!

    http://www.oracle.com/technetwork/articles/java/singleton-1577166.html

  69. Anonymous says:

    Thanxs for clearing my ideas about Singleton design pattern.

  70. Priya says:

    Kumar, since you ae creating the instance in the Singleton main class. The private constuctor is accessible. So that is why it is creating the second instance.

  71. Anonymous says:

    Please change the background colour of “Creational Design Patterns, Structural Design Patterns, Behavioural Design Patterns” :)

  72. Narendra says:

    instead of creating singleton if we do like this what will happen?

    “if we create object for class and after using that object if we assign Null to that object” and again create obj and after completing usage of that again assign null to it”.

  73. […] design pattern and singleton design pattern is used in implementing the […]

  74. ilia says:

    Hello, your tutorials are great. Can`t we singleton with static variable with check too? I mean, I want to put only one instance in a hashmap of let`s say MongoClient class, but I could`t do it with your code, so I came up with other sollution:
    private final static Map conn =
    new HashMap ();
    private static int instances = 0;
    public static void newConn(String host, int port) {
    if ( instances > 1 ) {
    System.err.println(“Only one instance allowed”);
    return;
    } else {
    try {
    instances++;
    conn.put(host, new MongoClient(host, port));
    } catch (UnknownHostException e) { e.printStackTrace(); }
    }
    }

    It worked for me creating only one instance and reference it by string… kind of what I needed. But don`t know about syncrho issues… Is it thread safe? Or must I add increment function (synchro) and volatile static variable?

  75. amit says:

    1st one is better solution because it is having lock on object as well as It is checking for instance then only try to capture Object lock (synchronized) while in second method it self is synchronized means it will take lock first then check if object is present or not. This will lead to slow performance – think of case when you have 1000s of object request coming- each one has to wait for lock before getting object while in first method every request gets object without acquiring lock.
    Hope this will help.

  76. Anonymous says:

    Ya its very helpfull…

  77. Anonymous says:

    good doc

  78. Mahaveer Prasad says:

    Very good explanation
    Thanks

  79. karthiga says:

    hi sir,
    how to use singleton pattern to open and close jdbc connection in java using oracle as backend

  80. Nitesh Gadekar says:

    Good explanation…! Sir

  81. Chelsea says:

    The above one, as it does double check before creating the singleton instance.
    COnsider there are 2 threads ,and both will reach before synchronized block .one of thread will enter and will check whether any instance is created or not,if there is no instance then it will create one .Once the thread one is done with the work it will release the lock,now thread 2 will enter in the synchronized block again it check whether any instance is already there or not ,it will get the earlier instance and will not create a new one.

  82. Chelsea says:

    Reflection will definitely break Singleton pattern. That is why readResolve() will come in picture.

  83. Ravi kishore says:

    good explanation Joe ,i am fan of your teaching style

  84. Davis says:

    Very helpful…Keep blogging !

  85. rafi says:

    in a real time projects where exactly used single tone class tell me one project example

  86. Suyash says:

    please anyone explain that what does mean by –
    synchronized(Singleton.class)

    I know about synchronized method and synchronized block. But i’m not able to understand the above usage of synchronization.

    please someone explain. Thanks !!

  87. Navin says:

    Hi Joe,

    This is really very simple & nice explanation.

    Many thanks!

  88. Neetha says:

    Good job. It’s very clear.

  89. ladd says:

    “It also takes care of the multithreading scenario.”
    I wonder that the static field was initialized thread safely when class loaded or not. And I heard that a static field would be initialized only once. If so, is it necessary to take multithread into account?

  90. […] Proxy design pattern gets second rank in popularity in interviews. Guess who gets the first rank? none other than singleton design pattern. […]

  91. sachin says:

    Cloning the object can still copy it and result into duplicate object.if i overload clone method than it’s compulsory to implements cloneable interface.

  92. Fareed Mohammed says:

    Hi Joe,

    This is really very simple & nice explanation.

    Thanks
    Fareed

  93. Rajnish Jha says:

    I think the second one as it contains less code…easy to summaries :D

  94. PB says:

    I think , the Singleton class will load at the starting of the program execution also the singleInstance as it is a static veriable. So there will not be any situation where that variable will be different.

  95. Ajit says:

    First one is better.
    Consider the multithreading scenario. The second method will always make other threads wait until one thread is executing it, regardless of a instance is already created or not.
    The first method will block other threads only once in the scenario where instance is not created yet. Once the instance is created, the synchronised block will never needed to be entered. Hence increasing the efficiency.

  96. Saad Afzal says:

    Nice Effort you did a great job…

  97. Padma says:

    Hi
    Its really nice article to learn about singleton pattern. i have a question that, is singleton pattern does have strict control over how and when client access it. I understand after read this article that it will have strict control on how client access the singleton object. But i m still confused on control on when client access singleton object, i think it can have control only in case singleton class is synchronized, and we can create singleton object without synchronization also if your application is single threaded environment. plz clarify

  98. Maddy says:

    Thanks Joe for such nice text…

    Here is an article on same topic

    “How to design Singleton Pattern using Java?
    Posted on February 10, 2014 by admin
    Singleton pattern is one most commonly used pattern in every types of software application developments. Therefore every interviewer would like to ask about this pattern first. This is really simple design pattern to create but you need to take care of some common things to design this pattern. Before going deep, let us concentrate on singleton pattern definition.”

  99. Venkataswamy says:

    Every class in Java has an associated instance of java.lang.Class that contains metadata about the class–its field names and types, method declarations, parent class, etc. When you see ClassName.class that is known as a class literal. It is a compile-time constant that evaluates to a reference to that class’s Class object.

  100. prashant says:

    I would like to ask a question about your example which is below:
    package com.javapapers.sample.designpattern;
    public class Singleton {
    private static Singleton singleInstance;
    private Singleton() {}
    public static Singleton getSingleInstance() {
    if (singleInstance == null) {
    synchronized (Singleton.class) {
    if (singleInstance == null) {
    singleInstance = new Singleton();
    }
    }
    }
    return singleInstance;
    }

    Q> why we want outer if() block when we are checking inside the synchronized block ?

  101. PROJJWAL says:

    The explanation is very nice and clear . It would be more better if you give an example of Multi-threading with Singleton (both Early and lazy instantiation ).Then I think it will be a complete article for Singleton.

  102. raj says:

    u can assign the value as null but there is a reference created for that object i mean some address is stored for that specific object so if you assign null and try to create a another object it will not create a new object even you can test it by printing the address of the object.

  103. Shivendra Namdeo says:

    Sound good..

  104. Arundev says:

    Always use method with Synchronized block. Second one contains only few lines of code but one issue with that is if two threads access the simultaneously both will initialize the object. To avoid this synchronization is used.
    Always better to practice with use synchronized part in Singleton classes.

  105. padmarao says:

    1 st one is better and it is perfomance wise it’s good.why?because
    if u are unnecessary acquiring the lock, if object is already there if u can return use this.why it is entire method is acquries a lock.
    this is perfomance issue.
    first one object is created,next one is entered it unnecessary to acquires the lock entire method……..
    so second one is gives a small perfomance issue

  106. Ashok S says:

    Your way of explanation is very simple and easy to understand for beginners as well as intermediate developers.
    Thanks for such a wonderful blog.

    Could you write about all Design Principles in Java like DRY (Don’t Repeat Yourself), Single Responsibility Principle.

    Also it would be helpful if there was an Android app for this website.

  107. Joe says:

    Thanks Ashok.

    Both are in queue. I trying to cover all design patterns one by one. The mobile app for Javapapers will be launched soon.

Comments are closed for this "Singleton Design Pattern" tutorial.