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.

View Comments

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

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

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

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

  • Hi,

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

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

  • [code language="java"]
    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();

    }
    }
    [/code]

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

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

Share
Published by
Viral Patel
Tags: Java Java design pattern Java singleton design pattern singleton singleton class

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago