Best Practices of Java Singleton Design Pattern

Singleton Pattern

We have different approaches but all of them have following common concepts to implement Singleton pattern:

  • Private constructor which restricts instantiation of the class from other classes.
  • Private static variable of the same class that is the only instance of the class.
  • Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.

Where do you use the Singleton pattern?

Most of the scenarios, Singleton classes are created for resources such as File System, Database connections etc…

Eager initialization

This is a good approach to use unless your singleton class is not using a lot of resources. In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class.

public class SimpleSingleton {
  public class SimpleSingleton {
     private static final SimpleSingleton instance = new SimpleSingleton();
     // private constructor to avoid client to use constructor
     private SimpleSingleton() {}
     public static SimpleSingleton getInstance() {
        return instance;
     }
  }
}

However, this approach has a drawback that instance is created even though client application might not be using it.

Static block initialization

This approach is very similar to above approach but the instance of class is created in the static block that provides option for exception handling.

public class StaticBlockSingleton {
	private static StaticBlockSingleton instance;
        // private constructor to avoid client to use constructor
	private StaticBlockSingleton() {}
	// static block initialization for exception handling
	static {
		try {
			instance = new StaticBlockSingleton();
		} catch (Exception e) {
			throw new RuntimeException(
					"Exception occured in creating Static Block singleton instance");
		}
	}
	public static StaticBlockSingleton getInstance() {
		return instance;
	}
}

As a conclusion, both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use! To improve the performance, we can use the lazy implementation of Singleton pattern.

Lazy Initialization

Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Therefore, This implementation works fine on single threaded environments. However, when this approach comes to multithreaded systems, this can cause problems if the mutual exclusion occurs and multiple threads are inside the critical section at the same time.

public class LazyInitializedSingleton {
	private static LazyInitializedSingleton instance;
	private LazyInitializedSingleton() {}
	public static LazyInitializedSingleton getInstance() {
		if (instance == null) {
			instance = new LazyInitializedSingleton();
		}
		return instance;
	}
}

This above implementation is a good approach but it is not a thread-safe singleton class. Here is the thread-safe implementation of Lazy Initialization singleton class.

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

This above implementation has a drawback which reduces the performance because of cost associated with the synchronized method!

Double Checked Locking Principle

In order to avoid cost of synchronized method every time, we can use the double checked locking principle. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of singleton class is created.

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

A different approach to create the Singleton class using a inner static helper class. This is best implementation for thread safe singleton pattern whereas this beats other patterns because MyClass.getInstance()!

public class SingletonHolder {
    private SingletonHolder(){}
    private static class SingletonHelper{
        private static final SingletonHolder INSTANCE = new SingletonHolder();
    }
    public static SingletonHolder getInstance(){
        return SingletonHelper.INSTANCE;
    }
}

The private inner static class that contains the instance of the singleton class. When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when client calls the getInstance method, this class gets loaded and creates the Singleton class instance.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s