Master java skills

Singleton Design Pattern

Singleton Design Pattern ensures that only one instance of a class can exist. 

In order to follow this design pattern, please follow below points:

  1. Make the constructor of the class private so that its instance can’t be created outside the class
  2. Keep a static instance of the class
  3. Provide a static method to access this instance
package com.sks;

public class MySingleton {

	private static MySingleton obj;
	
	private MySingleton() {

	}
	
	public static MySingleton getInstance() {
		if(obj == null) {
			obj = new MySingleton();
		}
		return obj;
	}

}

Now, let’s test this from a main method

package com.sks;

public class SingletonTest {
	
	public static void main(String[] args) {
				
		MySingleton obj1 = MySingleton.getInstance();
				
		MySingleton obj2 = MySingleton.getInstance();
		
		System.out.println(obj1 + " : " + obj2);
	}
}

Output: In the above code, we have printed the addresses of the two object, and we can see that they have same address.

Singleton in multithreading context

The above approach is fine in case of a single thread application, but the same is not going to work in a multithreaded application.

Double checked locking singleton

In case of multithreaded application, we use double checked locking mechanism to ensure that just one object is created. Below is the example

package com.sks;

public class MySingleton {

	private static MySingleton obj;

	private MySingleton() {

	}

	// double checked locking singleton
	public static MySingleton getInstance() {

		if (obj == null) {
			synchronized (MySingleton.class) {
				if (obj == null) {
					obj = new MySingleton();
				}
			}
		}
		return obj;
	}

}