Singleton Pattern – Java

Singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

The singleton pattern is one of the simplest design patterns. It involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance. Same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Singleton Class Diagram:

Singleton Pattern
Implementation:

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.

Lazy initialization process -

public class SingletonDemo {

	// Static member holds only one instance of the SingletonDemo class
	private static SingletonDemo singletonInstance;

	// SingletonDemo prevents any other class from instantiating
	private SingletonDemo() {
	}

	// Providing Global point of access
	public static SingletonDemo getSingletonInstance() {
		if (null == singletonInstance) {
			singletonInstance = new SingletonDemo();
		}
		return singletonInstance;
	}

	public void printSingleton(){
		System.out.println("Inside Singleton");
	}
}

SingletonDemo.getSingletonInstance().printSingleton(); then at the first time only an instance will be created. Second time onwards for all subsequent calls it will be referring to the same object and the getSingletonInstance() method returns the same instance of the SingletonDemo class which was created at the first time.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one.

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. All the subsequent threads will be prevented from being access the singleton instance while one thread in inside the method getSingletonInstance().

public class SingletonDemo {
	private static SingletonDemo singletonInstance = null;

	private SingletonDemo() {	}

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

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.

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

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. 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. This mechanism is called double checked locking.

Please note that double check locking might not work before Java 5. In such situation we can use eager loading mechanism.

Eager initialization -

If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization, which always creates an instance:

public class SingletonDemo {
    private static final Singleton singletonInstance = new Singleton();

    private SingletonDemo() {}

    public static SingletonDemo getInstance() {
        return singletonInstance;
    }
}

There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required. And the final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.

One Thought on “Singleton Pattern – Java

  1. John Doe on October 10, 2017 at 8:55 am said:

    `volatile` couldn’t be applied to methods. It only applies to fields. Core Java, 14.5.8: “The volatile keyword offers a lock-free mechanism for synchronizing access to an instance field. If you declare a field as volatile, then the compiler and the virtual machine take into account that the field may be concurrently updated by another thread.”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation