Singleton Design Pattern in Java

Let’s start the series on Design Pattern with the famous Singleton design pattern.

 What is design pattern?

A design pattern is a language independent proven solution for solving common object oriented design problems.   Why we say that it is proven solution? This is because each pattern describes a problem which occurs over and over again in the programming world and it describes a solution to that problem which can be used multiple times. These solutions have been time tested.

These design patterns are not specific to any language; however we can use the templates and guidelines laid down by this pattern and implement them in either C++, Java, PHP or any areas to resolve the Object Oriented Design problems.

In this series are will try to describe the Singleton pattern using Java.

Singleton has been a part of the GoF (Gang of Four) and is categorized under Creational Design Patterns.

Reference Notes:
What is a Creational design pattern?These design patterns are related to class instantiation, trying to create objects which are suitable for the situation.  Object creation can create some design problem and add more complexity to the design. This type of design pattern solves this problem somehow by controlling the object creation and help in abstraction of the instantiation process.

Problem statement:

Application needs one an only one instance of the object. There are many scenarios where we might need only one object e.g. caches, thread pools, objects used for logging, configuration settings and device driver objects for printers etc.

What are the consequences of not having single objects in the above cases?

Well, that means you might run up into issues in incorrect program behavior or inconsistent results. There might be wastage of valuable resources.

What do we need to resolve?

Singleton is here for the rescue. In this situation we will need to ensure only one instance of a class is created by the JVM.

  • Provide a Global point of access to the object.
  • This is exactly what Singleton design pattern is intended to do.

What does it need to implement a Singleton pattern in Java?

Singleton Implementation

Singleton Implementation

As mentioned in the above diagram we just need the following:

  • Static member – This holds the instance of the singleton class
  • Private constructor –  Nobody else can 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.
Singleton Class DiagramSingleton Class Diagram

 

 

 

 

 

 

 

 

Code Examples: SingletonExample.java implementing Singleton design pattern.

package com.singleton;

/**
 * Example of Singleton Class
 * @author IdioTechie
 */
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");
	}
}

The above getSingletonInstance() method ensures that there is only one instance of the class created, returned and it is accessed by the outer world through this public method. Since the constructor is private SingletonExample constructor will  not be accessed outside the class and will be accessed only through the getSingletonInstance() method.

Call to getSingletonInstance()Value of singletonInstance
First timesingletonInstance is null
Next time onwardsReturn same reference of singletonInstance object which was created

A client class (SingletonClient.java) which accesses SingletonExample.java.

package com.singleton;

/**
 * SingletonClient class for accessing SingletonExample
 * @author Idiotechie
 */
public class SingletonClient {

	public static void main(String[] args) {
		SingletonExample.getSingletonInstance().printSingleton();
	}
}

The singleton class can be accessed through getSingletonInstance() method.

This article gives a basic understanding and a standard implementation of Singleton. We will discuss on the specific implementation problems, using Singleton in multi threading, practical implementation examples in future our blog series. Hope our readers will like this article. So keep watching this space and don’t forget to provide your valuable comment.

8 Responses to “Singleton Design Pattern in Java”

  1. Javin

    Mar 04. 2012

    Singleton still remains a powerful core java pattern and has its place in between Static utility class. as you said classical example is JDK itself which provides both java.lang.Math and java.lang.Runtime differently. Though Singleton seems easy many programmer mess it up when asked write code for Singleton. I have shared few questions as 10 interview question on Singleton pattern in java let me know how do you find it.

    Reply to this comment
    • IdioTechie

      Mar 05. 2012

      This looks good Javin. Very useful for the Java Interviews. BTW I have shared a new article today on JMS. Let me know if you liked this new post.

      Reply to this comment
  2. Aditya

    Oct 15. 2012

    One correction – the ‘getInstance()’ method should be enhanced for double-checked locking in case of multi-threaded environment. As per current code, more than one thread can access this method and same instance and result in multiple objects of this class.

    Reply to this comment
  3. Will

    Jan 21. 2013

    Double checking is bad, even with Java 5 and the memory model.

    Either you should use static initialisers, or you really need a lazy initialisation of a singleton you should use the ‘Initialization On Demand Holder idiom’ and have the getInstance method to call an eager singleton of a holder (see http://blog.crazybob.org/2007/01/lazy-loading-singletons.html and http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#dcl).

    Reply to this comment

Trackbacks/Pingbacks

  1. Gang of Four (GoF) Design Pattern | IdioTechie - October 14, 2012

    [...] Singleton [...]

  2. Singleton Design Pattern An introspection and best practices | IdioTechie - February 12, 2013

    [...] Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns. In [...]

Leave a Reply