Java Singleton design pattern tutorial.

Java Singleton design pattern is one of the design pattern that governs the instantiation of an object in Java. This design pattern suggest that only one instance of a Singleton object is created by the JVM. This pattern is useful when exactly one object is needed to coordinate actions across the system. Also it can be generalized to restrict the objects to certain number of instances like say 5 objects only. Related: Free Design Pattern Reference Card

Class diagram of Singleton class

Following is the class diagram of a singleton class. The constructor is kept private to avoid normal instantiation of objects and all the instantiations are done only through getInstance() method.

How the Singleton pattern works?

Following is the source of simple class that follows singleton pattern.
public class SimpleSingleton { private static SimpleSingleton INSTANCE = new SimpleSingleton(); //Marking default constructor private //to avoid direct instantiation. private SimpleSingleton() { } //Get instance for class SimpleSingleton public static SimpleSingleton getInstance() { return INSTANCE; } }
Code language: Java (java)
In above code snippet, we have declared a static object reference to SimpleSingleton class called INSTANCE and is returned every time getInstance() is called. In this design, the object will be instantiate when the class will be loaded and before the method getInstance() is being called. Demand loading (lazy loading) also called initialization on demand holder idiom is not seen in this implementation. We can change this code to add lazy init (Instantiate only when first time getInstance() is called) into this. Following is the code snippet for that.
public class SimpleSingleton { private SimpleSingleton singleInstance = null; //Marking default constructor private //to avoid direct instantiation. private SimpleSingleton() { } //Get instance for class SimpleSingleton public static SimpleSingleton getInstance() { if(null == singleInstance) { singleInstance = new SimpleSingleton(); } return singleInstance; } }
Code language: Java (java)

Do you need Singleton pattern?

Singletons are useful only when you need one instance of a class and it is undesirable to have more than one instance of a class. When designing a system, you usually want to control how an object is used and prevent users (including yourself) from making copies of it or creating new instances. For example, you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern. The Singleton pattern is often used in conjunction with the factory method pattern to create a systemwide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Abstract Windowing Toolkit (AWT). In GUI applications, you often need only one instance of a graphical element per application instance, like the Print dialog box or the OK button.

Problems with Singletons

A simple design pattern like Singleton also has few problem:

Construct in a multi-thread environment

It may happen that in a multi-threaded environment two or more threads enter the method getInstance() at the same time when Singleton instance is not created, resulting into simultaneous creation of two objects. Such problems can be avoided by defining getInstance() method synchronized.
public static synchronized SimpleSingleton getInstance() { }
Code language: Java (java)

Cloning can spoil the game

Although we have taken enough precaution to make the Singleton object work as singleton, Cloning the object can still copy it and result into duplicate object. The clone of the singleton object can be constructed using clone() method of the object. Hence it is advisable to overload clone() method of Object class and throw CloneNotSupportedException exception.
public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
Code language: Java (java)
The Singleton pattern is widely used and has proved its usability in designing software. Although the pattern is not specific to Java, it has become a classic in Java programming.
Get our Articles via Email. Enter your email address.

You may also like...

19 Comments

  1. sud says:

    Singletons lead to hard to test systems. Read the following post and similar post by Misko Hevery for some insight?

    http://misko.hevery.com/2008/08/25/root-cause-of-singletons/

  2. Himanshu says:

    is it advisable to inherit a SingleTon Class..?

    • Muhammed Nuzli says:

      yes Himanshu, you can inherit the singleton class because the class is public. if it is final you cannot inherit any classes ok.
      Thanking you.

    • om says:

      This can be inherited but then the accessibilty of constructor should be made protected.And if we make the constructor protected then class can be extended by other class.
      But by making the constructor protected the singleton design is lost.

  3. Hi Himanshu,
    I believe singleton design pattern doesn’t disallow inheritance. Singleton guarantees single instance of a type and since derived class *is* its base type then inheritance is allowed as long as there is only one instance of the base (singleton) type. In other words only
    one instance of the singleton class or any of its derived classes can exist.

  4. dereke says:

    Hi
    I am trying to draw a singleton class diagram but do not understand uml too well. The singleton is to serve/ collaborate with a couple of other classes. Do I draw these other two classes next to the singleton class (and point an arrow towards each)?

    I’m a bit confused.

    Thanks for your help.

  5. abhijit says:

    Hi,

    Small correction needed in the given example. The non-static variable can not be used in the static context.

  6. Abinash says:

    how i write singleton class is run.

  7. Prerna Sancheti says:

    can one singleton class inherit other singleton class?

    • Muhammed Nuzli says:

      Hello Perna!
      do you mean can a singleton class can be inherit or not?
      yes Perna. you can inherit the singleton class because it is public ok.
      if it is final you cannot inherit the singleton class ok.
      Thanking you.

    • Mahesh Agrwal says:

      No it ll not

  8. kphari says:

    public class SimpleSingleton {
        private final SimpleSingleton singleInstance = null;
     
        //Marking default constructor private
        //to avoid direct instantiation.
        private SimpleSingleton() {
        }
     
        //Get instance for class SimpleSingleton
        public static synchronized SimpleSingleton getInstance() {
     
            if(null == singleInstance) {
                singleInstance = new SimpleSingleton();
            }
     
            return singleInstance;
        }
    public Object clone() throws CloneNotSupportedException {
     
          throw new CloneNotSupportedException();
     
    }
    }
    

    • Jimmy says:

      That is an inferior singleton due to the overhead of the get instance synchronisation. People used to use double checked locking to avoid the synchronisation issue but that never worked due to the java memory model, double checked locking was apparently fixed in java 1.5 but who cares?
      Singletons are generally considered an antipattern these days as sud mentioned, they result in hard to test code. We all use Dependency Injection nowadays and let the container control our object creation right?
      Here is a quick piece of career advice… next time you are in a job interview and they ask about design patterns: don’t mention Singleton! talk about Inversion Of Control or instead!

  9. Nice post. I had recently posted about about implementing Singleton using C#. It might be helpful for those who know both Java and C# or are interested in both the languages.

    http://www.nileshgule.com/2012/03/singleton-design-pattern.html

  10. Bogdan says:

    This design pattern is used for controlling the number of instances of a class (to one in general). This is maybe the first, the most used and the easiest design pattern out there.
    Beware that this control ( controlling the number of instances of a class ) is available per classloader, and not for JVM, not to say more when thinking at distributed topologies. This is because the final static instance variable – being static is per class basis. As you know now, in a JVM you can have more than one classloader – meaning you can load the same Singleton implementing class more than once (once per classloader). Loading more than once the Singleton implementing class results in the possibility of having n instances controlled by the singleton per JVM, where n represents the number of the loads of the Singleton implementing class, so will need at least n classloaders.
    In a multiple JVM topology ( cluster deployed application ) special algorithms must be taken into consideration for controlling the number of instances of a class. These can be fine-tuned depending on the needs of the application requirements.
    The Singleton design pattern can also be expressed as an eager implementation which is thread safe too. Using synchronized you can make it thread safe without the eager initialization.
    More at:
    http://centraladvisor.com/programming-2/design-patterns/what-is-singleton-pattern

    B/

  11. Sudipta says:

    Nice article dude..I am really a big fan of your java blogs..thanks..

  12. Alan Krueger says:

    The instruction to implement clone() to override CloneNotSupportedException seems superfluous. Unless you implement Cloneable in your class, that’s what the default Object.clone() method already does. (If you’ve implemented Cloneable on your singleton, why?)

  13. Beaumont Muni says:

    It’s better to use a double locking check construct to avoid multithreaded runs that create mulitple instances of your singleton. Simply expand a synchronized method to do the check one more time on the existence of an instance.

Leave a Reply

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