Singleton Design Pattern

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Singleton Pattern guarantees that only one Object is instantiated for a given class and provides a global point of access to this instance, so it avoid all sorts of problems likes program behavior, overuse of resources and other inconsistencies. This pattern is used for logging, database connections, file manager, configuration settings, caching and thread pool etc.

When to use Singleton design pattern

This pattern should use if you need only one instance of the class like in logging, database connections, file manager, configuration settings, caching and thread pool etc.

Singleton design pattern diagram:

singleton design pattern uml

Here are the points to remember in creating Singleton pattern

  • Create a private static variable of Singleton class. This is the only Instance of Singleton Class.
  • Create private constructor which make sure that outer class cannot instantiate object form Singleton Class.
  • Create a global method for getting the Singleton Instance.

You can create Singleton Pattern in many ways

Types of singleton implementations

  1. Eager initialization
  2. Static block initialization
  3. Lazy initialization
  4. Thread safe initialization
  5. Bill Pugh Inner Static
  6. Enum initialization

Eager Singleton Pattern:

The Singleton Instance will be created at the time of class loading into the JVM. But has disadvantage if no client class wants to use it after creating instance and will consume memory unnecessarily and cannot use exception handling.

package com.javatutsworld.singletondesignpattern;

public class EagerSingleton {

	private static EagerSingleton instance = new EagerSingleton();;

	private EagerSingleton() {

	}

	public static EagerSingleton getInstance() {
		return instance;
	}
	
	public void printHello(){
		System.out.println("Hello Saaim");
	}

}

package com.javatutsworld.singletondesignpattern;

public class AppTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		EagerSingleton eSingleton=EagerSingleton.getInstance();
		eSingleton.printHello();

	}

}

Output

Hello Saaim

Static Block Singleton Implementation

The Static Block Singleton Implementation is same as Eager Singleton Implementation; Instance is created at the Class loading time but can handle the exception inside the static block


package com.javatutsworld.singletondesignpattern;

public class StaticBlockSingleton {

	private static StaticBlockSingleton instance;

	private StaticBlockSingleton() {

	}

	static {
		try {
			instance = new StaticBlockSingleton();
		} catch (Exception e) {
			throw new RuntimeException("Exception handle here");
		}
	}

	public static StaticBlockSingleton getInstance() {
		return instance;
	}

	public void printHello() {
		System.out.println("Hello Aariz");
	}

}

package com.javatutsworld.singletondesignpattern;

public class AppTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StaticBlockSingleton stblockSingleton=StaticBlockSingleton.getInstance();
		stblockSingleton.printHello();

	}

}

Output


Hello Aariz

Lazy Singleton Implementation

Lazy Singleton Implementation will create Singleton Instance at the first time of Client call. This approach is good if application is single threaded but if multiple threads comes inside the loop at the same time then It will destroy the singleton pattern and both threads will get the different instances of this class.


package com.javatutsworld.singletondesignpattern;

public class LazySingleton {

	private static LazySingleton instance;

	private LazySingleton() {

	}

	public static LazySingleton getInstance() {
		if (instance == null) {
			instance = new LazySingleton();
		}
		return instance;
	}

	public void printHello() {
		System.out.println("Hello Ali");
	}

}

package com.javatutsworld.singletondesignpattern;

public class AppTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LazySingleton lazySingleton=LazySingleton.getInstance();
		lazySingleton.printHello();

	}

}

Output


Hello Ali

Thread Safe Singleton Pattern

Using synchronized on the method only one thread can execute this method at a time but this approach will down the performance


package com.javatutsworld.singletondesignpattern;

public class ThreadSafeSingleton {

	private static ThreadSafeSingleton instance;

	private ThreadSafeSingleton() {

	}

	public static synchronized ThreadSafeSingleton getInstance() {
		if (instance == null) {
			instance = new ThreadSafeSingleton();
		}
		return instance;
	}

	public void printHello() {
		System.out.println("Hello Norej");
	}

}

package com.javatutsworld.singletondesignpattern;

public class AppTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadSafeSingleton thSafeSingleton=ThreadSafeSingleton.getInstance();
		thSafeSingleton.printHello();

	}

}

Output


Hello Norej

Double locking

With using synchronized on the method, the synchronized lock always is checked then making down up performance so Double Checking Implement below will resolve the problem. You first check to see if an instance is created or not, and if it is null, then you synchronize. This way, you only synchronize the first time.


package com.javatutsworld.singletondesignpattern;

public class DoubleLockSingleton {

	private static DoubleLockSingleton instance;

	private DoubleLockSingleton() {

	}

	public static DoubleLockSingleton getInstance() {
		if (instance == null) {
			synchronized (DoubleLockSingleton.class) {
				if (instance == null) {
					instance = new DoubleLockSingleton();
				}
			}

		}
		return instance;
	}

	public void printHello() {
		System.out.println("Hello Arhan");
	}

}

package com.javatutsworld.singletondesignpattern;

public class AppTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	DoubleLockSingleton doubleLockSingleton=DoubleLockSingleton.getInstance();
	doubleLockSingleton.printHello();

	}

}

Output


Hello Arhan

Bill Pugh Singleton Pattern

Java memory model has lots of issues when having too many threads trying to get Instance, so Bill Pugh gives a new approach using inner static class and this inner class will not load into memory with outer class, this only will load when client calls the getInstance() method of the class.


package com.javatutsworld.singletondesignpattern;

public class InnerStaticSingleton {

	private InnerStaticSingleton() {

	}

	private static class SingletonInner {
		private static final InnerStaticSingleton instance = new InnerStaticSingleton();
	}

	public static InnerStaticSingleton getInstance() {
		return SingletonInner.instance;
	}

	public void printHello() {
		System.out.println("Hello Ibrahim");
	}

}

package com.javatutsworld.singletondesignpattern;

public class AppTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		InnerStaticSingleton innerStaticSingleton=InnerStaticSingleton.getInstance();
		innerStaticSingleton.printHello();

	}

}

Hello Ibrahim

Enum Singleton Pattern

Joshua Bloch suggests the use of Enum to implement Singleton design pattern, so after JDK 1.5, you can create a singleton class using enum. The Enum constants are implicitly static and final and you cannot change their values once created.


package com.javatutsworld.singletondesignpattern;

public enum EnumSingleton {
	 
	INSTANCE;
 
    public void  Print(){
        System.out.println("Hello  Ji");
    }
}

package com.javatutsworld.singletondesignpattern;

public class AppTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		EnumSingleton.INSTANCE.Print();
		
	}

}

Output


Hello  Ji

Here are some other ways to break the singleton pattern.

  1. During the Deserialization if class is Serializable.
  2. During if class is Clonable.
  3. Using Reflection.
  4. If class is loaded by more than one class loaders.

Here is the example where you can protect the class from getting instantiated more than once.


package com.javatutsworld.singletondesignpattern;

import java.io.ObjectStreamException;
import java.io.Serializable;

public class SingletonBreak implements Serializable{
	private static final long serialVersionUID = -1093810940935189395L;
	private static SingletonBreak singletonBreak = new SingletonBreak();
	private SingletonBreak(){
		if(singletonBreak!=null){
			throw new IllegalStateException("Intances is created already.");
		}
	}
	public static SingletonBreak getInstance(){
		return singletonBreak;
	}
	
	private Object readResolve() throws ObjectStreamException{
		return singletonBreak;
	}
	
	private Object writeReplace() throws ObjectStreamException{
		return singletonBreak;
	}
	
	public Object clone() throws CloneNotSupportedException{
		throw new CloneNotSupportedException("This is Singleton class so cannot be clonned");
	}
	
	private static Class getClass(String cname) throws ClassNotFoundException {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if(classLoader == null) 
			classLoader = SingletonBreak.class.getClassLoader();
		return (classLoader.loadClass(cname));
	}

}

In the above example if you use these methods then no one create multiple instance of the class

  • If you implement these two methods readResolve() and writeReplace() in the singleton class then this class return the same object.
  • If you implement the method clone() and throw an exception then this class cannot be cloned.
  • If you check the instance is present inside the constructor then nobody can create more than one instance using reflection.
  • You implement the getClass() method which contacts the classloader with the current thread, if that classloader is null then method uses the same classloader that loaded the singleton class. In this way you prevent the singleton getting instantiated from different class loaders.
Here are methods which uses Singleton Design Pattern in JDK
  • java.lang.Runtime#getRuntime()
  • java.awt.Toolkit#getDefaultToolkit()
  • java.awt.Desktop#getDesktop()
For more details please see
Head First Design Patterns
      Advertisements