Enterprise Integration Zone is brought to you in partnership with:

Mainak is an experienced Technology Consultant specializing in JEE, Web Development and Open source technologies. He is currently based out of United Kingdom. He is die hard technology enthusiast trying to explore the latest in the world of technology. In past time he loves blogging on his website: http://idiotechie.com. Mainak is a DZone MVB and is not an employee of DZone and has posted 11 posts at DZone. You can read more from them at their website. View Full User Profile

Singleton Design Pattern – An Introspection w/ Best Practices

02.13.2013
| 196779 views |
  • submit to reddit
Definition:
Singleton
is a part of Gang of Four design pattern and it is categorized under creational design patterns.

In this article we are going to take a deeper look into the usage of the Singleton pattern. It is one of the most simple design pattern in terms of the modelling but on the other hand this is one of the most controversial pattern in terms of complexity of usage.

In Java the Singleton pattern will ensure that there is only one instance of a class is created in the Java Virtual Machine. It is used to provide global point of access to the object. In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects. Design pattern is often used in conjunction with Factory design pattern. This pattern is also used in Service Locator JEE pattern.

Structure:
Singleton Class Diagram

Singleton Class Diagram

  • Static member : This contains the instance of the singleton class.
  • Private constructor : This will prevent anybody else to instantiate the Singleton class.
  • Static public method : This provides the global point of access to the Singleton object and returns the instance to the client calling class.

Implementation Example: Lazy initialization

Let us look into a singleton implementation example in Java. The below code uses Lazy initialization process.

public class SingletonExample {
 
    // Static member holds only one instance of the
    // SingletonExample class
    private static SingletonExample singletonInstance;
 
    // SingletonExample prevents any other class from instantiating
    private SingletonExample() {
    }
 
    // Providing Global point of access
    public static SingletonExample getSingletonInstance() {
        if (null == singletonInstance) {
            singletonInstance = new SingletonExample();
        }
        return singletonInstance;
    }
 
    public void printSingleton(){
        System.out.println("Inside print Singleton");
    }
}
Singleton Pattern Code Explanation

Singleton Pattern Code Explanation

When this class will be called from the client side using SingletonExample.getSingletonInstance().printSingleton(); then at the first time only an instance will be created. During second time onwards for all subsequent calls we will be referring to the same object and the getSingletonInstance() method returns the same instance of the SingletonExample class which was created during the first time. You can test this by adding a print statement the following code as:

public static SingletonExample getSingletonInstance() {
        if (null == singletonInstance) {
            singletonInstance = new SingletonExample();
            System.out.println("Creating new instance");
        }
        return singletonInstance;
    }

If we now call Singleton class from the client class as:

SingletonExample.getSingletonInstance().printSingleton();
SingletonExample.getSingletonInstance().printSingleton();
SingletonExample.getSingletonInstance().printSingleton();
SingletonExample.getSingletonInstance().printSingleton();

The output of the above call is:

Creating new instance
Inside print Singleton
Inside print Singleton
Inside print Singleton
Inside print Singleton

Implementation Example: Double check locking

The above code works absolutely fine in a single threaded environment and processes the result faster because of lazy initialization. However the above code might create some abrupt behaviour in the results in a multithreaded environment as in this situation multiple threads can possibly create multiple instance of the same SingletonExample class if they try to access the getSingletonInstance() method at the same time. Imagine a practical scenario where we have to create a log file and update it or while using a shared resource like Printer. To prevent this we must use some locking mechanism so that the second thread cannot use this getInstance() method until the first thread has completed the process.

Singleton in heap

Singleton in heap

In Figure 3 we show how multiple threads access the singleton instance. Since the singleton instance is a static class variable in the stored in the PermGen space of the heap. This applies to getSingletonInstance() instance method as well since it is static too. In the multithreading environment to prevent each thread to create another instance of singleton object and thus creating concurrency issue we will need to use locking mechanism. This can be achieved by synchronized keyword. By using this synchronized keyword we prevent Thread2 or Thread3 to access the singleton instance while Thread1 inside the method getSingletonInstance().

From code perspective it means:

public static synchronized SingletonExample getSingletonInstance() {
        if (null == singletonInstance) {
            singletonInstance = new SingletonExample();
        }
        return singletonInstance;
    }

So this means that every time the getSingletonInstance() is called it gives us an additional overhead . To prevent this expensive operation we will use double checked locking so that the synchronization happens only during the first call and we limit this expensive operation to happen only once. It is only required for:

singletonInstance = new SingletonExample();

Code example:

public static volatile SingletonExample getSingletonInstance() {
        if (null == singletonInstance) {
            synchronized (SingletonExample.class){
                    if (null == singletonInstance) {
            singletonInstance = new SingletonExample();
            }
        }
        }
        return singletonInstance;
    }

In the above code snippet imagine that multiple threads comes concurrently and tries to create the new instance. In such situation the may be three or more threads are waiting on the synchronized block to get access. Since we have used synchronized only one thread will be given access. All the remaining threads which were waiting on the synchronized block will be given access when first thread exits this block. However when the remaining concurrent thread enters the synchronized block they are prevented to enter further due to the double check : null check. Since the first thread has already created an instance no other thread will enter this loop.

All the remaining threads that were not lucky to enter the synchronized block along with the first thread will be blocked at the first null check. This mechanism is called double checked locking and it provides significant performance benefit and also it is cost effective solution.

Implementation Example: Volatile Keyword

We can also use the volatile keyword to the instance variable declaration.

private volatile static SingletonExample singletonInstance;

The volatile keyword helps as concurrency control tool in a multithreaded environment and provides the latest update in a most accurate manner.However please note that double check locking might not work before Java 5. In such situation we can use early loading mechanism. If we remember about the original sample code we had used lazy loading. In case of early loading we will instantiate the SingletonExample class at the start and this will be referred to the private static instance field.

public class SingletonExample {
    private static final SingletonExample singletonInstance = new SingletonExample;
 
    // SingletonExample prevents any other class from instantiating
    private SingletonExample() {
    }
 
    // Providing Global point of access
    public static SingletonExample getSingletonInstance() {
 
        return singletonInstance;
    }
 
    public void printSingleton(){
        System.out.println("Inside print Singleton");
    }
}

In this approach the singleton object is created before it is needed. The JVM takes care of the static variable initialization and ensures that the process is thread safe and that the instance is created before the threads tries to access it. In case of Lazy loading the singletonInstance is created when the client class calls the getSingleInstance() whereas in case of the early loading the singletonInstance is create when the class is loaded in the memory.

Implementation Example: Using enum

Implementing Singleton in Java 5 or above version using Enum:
Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment. Let us see a simple implementation:

public enum SingletonEnum {
 INSTANCE;
 public void doStuff(){
     System.out.println("Singleton using Enum");
 }
}
And this can be called from clients :
public static void main(String[] args) {
        SingletonEnum.INSTANCE.doStuff();
 
    }

FAQs:

Question: Why can’t we use a static class instead of singleton?
Answer:

  • One of the key advantages of singleton over static class is that it can implement interfaces and extend classes while the static class cannot (it can extend classes, but it does not inherit their instance members). If we consider a static class it can only be a nested static class as top level class cannot be a static class. Static means that it belongs to a class it is in and not to any instance. So it cannot be a top level class.
  • Another difference is that static class will have all its member as static only unlike Singleton.
  • Another advantage of Singleton is that it can be lazily loaded whereas static will be initialized whenever it is first loaded.
  • Singleton object stores in Heap but, static object stores in stack.
  • We can clone the object of Singleton but, we can not clone the static class object.
  • Singleton can use the Object Oriented feature of polymorphism but static class cannot.

Question: Can the singleton class be subclassed?
Answer: Frankly speaking singleton is just a design pattern and it can be subclassed. However it is worth to understand the logic or requirement behind subclassing a singleton class as the child class might not inherit the singleton pattern objective by extending the Singleton class. However the subclassing can be prevented by using the final keyword in the class declaration.

Question: Can there be multiple instance of singleton using cloning?
Answer: That was a good catch! What do we do now? To prevent the another instance to be created of the singleton instance we can throw exception from inside the clone() method.

Question: What is the impact if we are creating another instance of singleton using serialization and deserialization?
Answer: When we serialize a class and deserialize it then it creates another instance of the singleton class. Basically as many times as you deserialize the singleton instance it will create multiple instance. Well in this case the best way is to make the singleton as enum. In that way the underlying Java implementation takes care of all the details. If this is not possible then we will need to override the readobject() method to return the same singleton instance.

Question: Which other pattern works with Singleton?
Answer:There are several other pattern like Factory method, builder and prototype pattern which uses Singleton pattern during the implementation.

Question: Which classes in JDK uses singleton pattern?
Answer: java.lang.Runtime : In every Java application there is only one Runtime instance that allows the application to interface with the environment it is running. The getRuntime is equivalent to the getInstance() method of the singleton class.

Uses of Singleton design pattern:

Various usages of Singleton Patterns:

  • Hardware interface access: The use of singleton depends on the requirements. However practically singleton can be used in case external hardware resource usage limitation required e.g. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock.

  • Logger : Similarly singleton is a good potential candidate for using in the log files generation. Imagine an application where the logging utility has to produce one log file based on the messages received from the users. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file. We can use the logger utility class as a singleton and provide a global point of reference.

  • Configuration File: This is another potential candidate for Singleton pattern because this has a performance benefit as it prevents multiple users to repeatedly access and read the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file at the first time and there after from second call onwards the client applications read the data from in-memory objects.

  • Cache: We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object.

Hands-on:

Let us take a small practical example to understand the Singleton design pattern in more details.

Problem Statement:
Design a small ATM printing application which can generate multiple types of statements of the transaction including Mini Statement, Detailed statement etc. However the customer should be aware of the creation of these statements. Ensure that the memory consumption is minimized.

Design Solution:
The above requirement can be addressed using two core Gang of four design pattern – Factory design pattern and Singleton design pattern. In order to generate multiple types of statements for the ATM transactions in the ATM machine we can create a Statement Factory object which will have a factory method of createStatements(). The createStatements will create DetailedStatement or MiniStatement objects.

The client object will be completely unware of the object creation since it will interact with the Factory interface only. We will also create an interface called StatementType. This will allow further statement type objects e.g. Credit card statement etc to be added. So the solution is scalable and extensible following the object oriented Open/Closed design principle.

The second requirement of reducing the memory consumption can be achieved by using Singleton design pattern. The Statement Factory class need not be initiated multiple times and a single factory can create multiple statement objects. Singleton pattern will create a single instance of the StatementFactory class thus saving memory.

ATM example

ATM example

  • Factory: Factory is an abstract class which is a single point of contact for the client. All the concrete factory classes needs to implement the abstract factory method.

  • StatementFactory: This is the Factory implementation class which consist of the creator method. This class extends from the Factory abstract class.This is the main creator class for all the products e.g. Statements.

  • StatementType: This is a product interface which provides abstraction to the various types of products which needs to be created by the Factory class.

  • DetailedStatement: This is a concrete implementation of the StatementType interface which will print the detailed statements.

  • MiniStatement: This is a concrete implementation of the StatementType interface which will print the mini statements.

  • Client: This is the client class which will call the StatementFactory and StatementType and request for object creation.

Assumption:
The design solution caters to only single ATM machine.

Published at DZone with permission of Mainak Goswami, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Niklas Efternamn replied on Wed, 2013/02/13 - 8:42am

Your following statement is incorrect: "In Java the Singleton pattern will ensure that there is only one instance of a class is created in the Java Virtual Machine", when using static menbers. It is only true per Class Loader, not JVM.

Stoo Mcstooo replied on Wed, 2013/02/13 - 10:05am

Double checked locking doesn't work well in java. See Java Concurrency in Practice, page 349 which recommends against it. At minimum the singleton should be volatile to work, and even then the performance improvement is negligible.

Dapeng Liu replied on Wed, 2013/02/13 - 12:03pm

singletons should really be managed by DI containers


Mainak Goswami replied on Wed, 2013/02/13 - 2:43pm in response to: Niklas Efternamn

Thanks Niklas. You are correct. Static deals with per class basis so when using static members it will be per class loader basis. However imagine the situation where there is only one application in the JVM which is used by this class loader. So implicitly singleton will have a unique instance throughout the JVM...isn't it? Please let me know your thoughts.

Mainak Goswami replied on Wed, 2013/02/13 - 2:44pm in response to: Stoo Mcstooo

Thanks Stoo. Perhaps this is the reason why I have mentioned that enum will be a most preferred option.

Gauthier Jacques replied on Thu, 2013/02/21 - 10:16am

Singleton is an anti-pattern and should never be used. Using an IoC container such as Spring instead is much more efficient, easy, secure, modular.

Mainak Goswami replied on Thu, 2013/02/21 - 1:46pm in response to: Gauthier Jacques

HI Gauthier,

Thanks for your reading this article. The point you have made is debatable and controversial. This was, is and will be one of the most debatable topic. 

Anyways enjoy reading.

Oleksandr Alesinskyy replied on Wed, 2013/02/27 - 8:08am

A code example

public static volatile SingletonExample getSingletonInstance()

is incorrect - "volatile" keyword is intended for variables only.

Mainak Goswami replied on Wed, 2013/02/27 - 1:49pm in response to: Oleksandr Alesinskyy

Agree. That was a typo.

Miguel Reboiro-jato replied on Thu, 2013/02/28 - 4:55am

I think that in Java, in most cases, there is no real advantage on using the "lazy" version instead of the "early" version. In Java, the static fields are not initialized until the class is used for the first time, and in the singleton pattern the class is usually used for the first time when the "getSingleton()" method is invoked. So, the "instance" field will be initialized at the same execution time in both cases. Therefore, I think that the "early" version is better, as the "if" statements are uneeded.

Lokesh Gupta replied on Wed, 2013/03/06 - 6:01am

 A very good article indeed. I also wrote an article covering above techniques and few more here.

http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/


My favorite is bill pugh solution using inner class to maintain singleton.

Michael Nitschke replied on Mon, 2013/03/18 - 11:36am

Singletons are an antipattern. Point! For over six years now.

The only debate that is going on about Singletons around here, is if they are just bad or evil as a goto.

Most of the time you get a better, more elegant solution when you try to avoid it. (As it is usual the case if you are experiencing a code smell)

Cheers Mike

Amit Shukla replied on Tue, 2013/05/07 - 9:17pm

Mainak, Can we break singleton using reflection?

And why is double locking not safe? I think these two points are missing, esp the first one.


Mainak Goswami replied on Fri, 2013/05/10 - 3:53pm

Hi Amit,

Thanks for your query.

To reply to your first question - Yes you can break the singleton using reflection. But there are ways to prevent the reflection attack. I think use of enum can prevent the reflection attack.

answering second question - double checked locking is not safe way of implementing singleton because the jvm have some flexibility of controlling the behavior in a multithreaded environment....specially in java versions 1.4 and before this inconsistency has been found....

Hope this helps.

Thanks

Shekhar Gupta replied on Wed, 2013/05/15 - 7:15am

Hi mainak,

I dont think we can subclass a Singleton class. The reason I see behind that is for private constructor it has. Whenever you extend any single ton class, its constructor would not be visible to it's child. So It can't extend it.

Mainak Goswami replied on Wed, 2013/05/15 - 2:33pm in response to: Shekhar Gupta

Hi Shekhar,

Thanks for your response.  To answer your question I would say that singleton will restrict the instances but it does not restrict inheritance. It may not serve any practical purpose but it is possible to extend a singleton class.

Imagine the situation if you have a anonymous subclass or imagine that you have other methods in the class which are not private - perhaps you can use them. As I said in my article until you use final keyword you can go ahead an subclass it. 

Hope this clarifies.


Shekhar Gupta replied on Sun, 2013/05/19 - 5:31am in response to: Mainak Goswami

Hi Mainak,

I guess I'm pretty sure that you can't inherit any Singleton class because of fact that it does have a private constructor. I shall be delighted if you counter my argument with any example.

Mainak Goswami replied on Sun, 2013/05/19 - 4:57pm in response to: Shekhar Gupta

Hi Shekhar,

You can create an inner class which inherits from the parent Singleton class.

class TestInnerClass extends SingletonExample{   } In the client calling class you can check if the TestInnerClass IS-A SingletonExample relationship using instanceof variable. Hope this helps.

Markus Kolb replied on Fri, 2013/05/24 - 7:13am

 Why there is never ever a reference to this solution...?

http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh 

It is thread-safe without any volatile magic or sync-overhead and it is initialized lazy.

Gauthier Jacques replied on Fri, 2013/05/24 - 7:56am

I totally agree with you. Even though I maintain that singletons are among the worst design mistakes I made when I was a junior, the Bill Pugh solution seems to be the most elegant one.

Oleksandr Alesinskyy replied on Fri, 2013/05/24 - 8:52am in response to: Gauthier Jacques

 The problem is that starting from Java 7 this solution cannot guarantee that singleton is a singleton (for reasons explained here http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.7



Gauthier Jacques replied on Fri, 2013/05/24 - 9:28am in response to: Oleksandr Alesinskyy

 Then back to square 1 : use IoC container and not singletons ! :-)

Markus Kolb replied on Fri, 2013/05/24 - 9:40am in response to: Oleksandr Alesinskyy

 Perhaps you can be more specific?!

Are you talking about class reloading?

The code says:

public static final Singleton INSTANCE = new Singleton();

The final says INSTANCE is INSTANCE and stays INSTANCE, doesn't it?

So reloading should be transparent in this case?!


Manoj Kumar replied on Tue, 2013/07/09 - 3:51am

 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.in/ for more details on this

Dinesh Bansal replied on Sat, 2013/08/10 - 2:09am

design problem is awesome. I was aware of singleton and factory pattern but did not know to apply them. Good article to understand the application of patterns.


Mainak Goswami replied on Sat, 2013/08/10 - 1:32pm

Thanks Dinesh for your feedback. Please keep visiting my space for more articles.

Andrew W replied on Wed, 2013/08/14 - 11:57pm

You only need to use the final keyword. Singletons are in use all over the JRE, files for examples, or have you ever used a filesystem that had two different files with the same path?

final File singleton = new File( "/tmp/test-it" );

 

some of your commenters were pretty rude, and pretty wrong.

How are you going t use this singleton, btw?

 

Dru

 

Srujana Mardi replied on Sun, 2013/09/15 - 8:43am

Hi Mainak,

Thanks for your blog. Sequence of steps which you explained is very easy to understand. with your article I have cleared all of my doubts but having doubt on using "volatile" keyword in double checked logging scenario. could you please let me know what exactly volatile and reason for using volatile in static method getSingletonInstance() method. Thanks for your response.



Henkz Sall replied on Sun, 2014/03/02 - 2:58pm in response to: Niklas Efternamn

willy filmes online shows a flow chart from the book co-authored by Charlie Hunt and Binu John. This chart shows the process of Java application performance tuning.

Henkz Sall replied on Sat, 2014/03/08 - 8:35pm

What youre indicating is utterly correct. I realize which anyone must filmes online

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.