by BehindJava

What is Singleton Design Pattern in Java

Home » java » What is Singleton Design Pattern in Java

In this tutorial we are going to learn about Singleton Design Pattern in Java with an example.

This is one of the famous and simplest design pattern. The main intent of this design pattern is to ensure that a class has only one instance is created all over the application and there is a global point for the accessing. Here the object is initialized on the first use.

Below shows a simple singleton class called SingletonObject and it is called from the class called MainClass.

public class SingletonObject {
 private static SingletonObject instance;
 private SingletonObject(){}
 
 public static SingletonObject getInstance(){
  if(instance == null){
   instance = new SingletonObject();
  }
  return instance;
 }
 public String sayHello(){
  return "Singleton Worked !!!";
 }
}

public class MainClass {
public static void main(String[] args) {
 SingletonObject singleton = SingletonObject.getInstance();
 System.out.println(singleton.sayHello());
}
}

Here what happening is the MainClass can’t initialize the SingletonObject directly because the constructor of SingletonObject is private so it can’t access from outside. So the MainClass try to initialize the SingletonObject using the getInstance() static method inside SingletonObject class. The getInstance() method tries to check if the instance of SingletonObject already initialized or not if it is not initialized yet then it will create a new instance of the corresponding class and return it.

But the above SingletonObject class having some loopholes are there for proving it was not singleton which are.

  1. If multiple threads are accessing the getInstance() method at a time then there is a possibility of duplication of instance
  2. It is also possible to duplicate an object by overriding the clone() method so in that case it becomes not singleton

To resolve the above issues, we need to alter the code for SingletonObject little bit. Below shows the changed code.

//The synchronized keyword is for the thread safety
 public static synchronized SingletonObject getInstance(){
  if(instance == null){
   instance = new SingletonObject();
  }
  return instance;
 }
 public String sayHello(){
  return "Singleton Worked !!!";
 }
 
 //This method is to restrict the object creation by using clone method
 @Override
 protected Object clone() throws CloneNotSupportedException{
  throw new CloneNotSupportedException();
 }
}