Code Pumpkin

Singleton Design Pattern

Subscribe

In Design Pattern article we have seen different types of design pattern available. In this article we will take one of the simplest design pattern from the Creational Design Pattern. Singleton Design Pattern is part of the creational design pattern. In Singleton design pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. So when we want to address a problem where we want to make sure that the only single instance of the given class gets created, we will use this design pattern.

Singleton Design Pattern Application:

  • Logging/caching mechanism
  • Thread pool creation
  • Singleton pattern widely used in creation of other design pattern as well(Ex. Factory, Builder, Prototype Patterns).
  • Creation of state objects


To make a class singleton in Java there below things to be taken care:

  • Define all constructors to be protected or private.
  • Define a private static attribute in the "single instance" class.
  • Define a public static accessor function in the class.
  • Do "lazy initialization" (creation on first use) in the accessor function.
  • Clients may only use the accessor function to manipulate the Singleton.

There are many ways using which we can make the class singleton:

  • Eager initialization
  • Lazy Initialization
  • Static block initialization
  • Thread Safe Singleton
  • Enum Singleton


Eager Initialization: As the name suggest, initialization of the instance is done at the time of class loading. But there are chances that even the instance is created client application may not use the created instance throughout the cycle. This is the disadvantage of the eager initialization. Code for this is given in below code:
 


package designpatterns.creational;

public class EagerInitializedSingleton{

        //Private static instance is created at the time of class loading
	private static EagerInitializedSingleton instance = new EagerInitializedSingleton();
	

        // Constructor made private so that no new instance can be created
	private EagerInitializedSingleton(){
		
	}
	
       // Static method to return the instance to the client
	public static EagerInitializedSingleton getInstance(){
		return instance;
	}
}

In practice one should be avoid using this approach as in most of the cases the pattern implementation will be for resource heavy. It is preferred to initialize instance when clients asked for it.

Lazy Initialization: This is same as simple as eager initialization, here only difference is  we create the instance when client first time asked for it. The implementation is shown below:
 


package designpatterns.creational;

public class LazzyInitializedSingleton{

        private static LazzyInitializedSingletoninstance;
	
	private LazzyInitializedSingleton(){
		
	}
	//Lazy initialization is done when client firt time request for the instance
	public static LazzyInitializedSingletongetInstance(){
		if(instance == null){
			instance = new LazzyInitializedSingleton();
		}
		return instance;
	}
}

Static block initialization: Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling. Below is the implementation:


package designpatterns.creational;

public class StaticBlockSingleton {

	private static StaticBlockSingleton instance;
	
	private StaticBlockSingleton(){
		
	}
	
	static{
        try{
            instance = new StaticBlockSingleton();
        }catch(Exception e){
            throw new RuntimeException("Exception occured in creating instance");
        }
    }
	
	public static StaticBlockSingleton getInstance(){
		return instance;
	}
}

All the above implementation will work when the given environment is single threaded. In case of the multithreaded environment we need to make it synchronized. In the next section we will see how we can make it thread safe.

Thread Safe Singleton: To make the singleton implementation thread safe, we will make the global accesser method thread safe. This will make our implementation thread safe. The implementation is as below:


package designpatterns.creational;

public class ThreadSafeSingleton {

	private static ThreadSafeSingleton instance;

	private ThreadSafeSingleton(){
		
	}

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

Above all implementations are having one issue. If we use reflections, we can break the singleton behaviour of the above implementations. 

Serializable Sigleton: To make a singleton class that is implemented using either of the previous approaches serializable, it is not sufficient merely to add implements Serializable to its declaration.Because it will create new instance of the object when it gets deserialized. To maintain the singleton guarantee, you have to declare all instance fields transient and provide a readResolve method. Otherwise, each time a serialized instance is deserialized, a new instance will be created. To prevent this, add this readResolve method to the singleton class in addition to implementing the Serializable interface.



protected Object readResolve() {
    return getInstance();
}

The above implementation will guarantee a singleton behaviour in case of serializatoin as well.

Enum Singleton: To overcome the issue with the previous implementation of reflection. Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization. The implementation is as below:


package com.codepumkin.singleton;

public enum EnumSingleton {

    INSTANCE;
    
    public static void doSomething(){
        //Some code here
    }
}

These are the some of the implementation for the singleton pattern.  The above implementations still having one problem. What if we clone the objects?  Yeah… We are able to create a second object without the need of the constructor or getInstance(). So pure implementation of singleton should also take care of the cloning of the objects. Can you try yourself to handle this particular situation in case of Lazy Initialization.

Happy Learning 🙂

Download Complete Java Program »

Tags: , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank