Singleton pattern

Singleton pattern

software_development

The singleton pattern allows us to create an object that has only one instance on the entire application and that is globally available.

How to do

How can we allow the creation of only one instance of an object? First, we make the constructor of the class private.


public class Singleton {
	private Singleton() {};
}

If we cannot instantiate an object with a constructor we could have a static method that returns us an instance of the object.


public class Singleton {
	public static Singleton getInstance() {
		return new Singleton();
	}
}

In this way we can call the class method Singleton.getInstance() to have a Singleton object. Every time the method is called though, we receive a new instance. The solution is to add a class field that contains the one and only instance of the object.


public class Singleton {
	private static Singleton instance;

	private Singleton() {};

	public static Singleton getInstance() {
		return this.instance;
	}
}

The instance is not initialized yet. Here we have two possible solutions, let’s see them:


public class Singleton {
	private static Singleton instance = new Singleton();

	private Singleton() {};

	public static Singleton getInstance() {
		return this.instance;
	}
}

public class Singleton {
	private static Singleton instance;

	private Singleton() {};

	public static Singleton getInstance() {
		if (this.instance == null) {
			this.instance = new Singleton();
		}

		return this.instance;
	}
}

The most used solution is the second, though it can result in some concurrency problem if we have a multithread application and two or more threads are accessing the getInstance() method on the same time. In the first solution the instance is always created when the classes is loaded, before any other object can use it. There is however a way to make the second solution thread safe.


public class Singleton {
	private static volatile Singleton instance;

	private Singleton() {};

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

		return this.instance;
	}
}

The synchronized keyword allow the access of the block below to only one thread at the time. Also, by making the instance volatile, we make the singleton object not cacheable and every time the object will be used the program will act as the object is in a synchronized block.

Related News