Singleton Design Pattern With Java Sample

What is Singleton Design Pattern?

 
Singleton design pattern is a creational design pattern. It is used to maintain single instance throughout the application.
 

When to use Single Design pattern?

 
When our requirement requires a single instance through the application and if it has to inherit by some other interface/class and if it needs memory management it should be dynamic and we can take steps to implement this design pattern.
 
If our aim is to create only single instance I recommend to use static class.
 

Where we can use it?

 
For Database connection, logging, caching purpose etc.
 

Rules to implement Singleton

  1. It should have Global access
  2. It should be not be inherited by some other class; i.e. we have to seal the class with Final key word / we can make constructor private to stop inheritance.
  3. Constructor should be Private, to prevent the creation of instance from outside the class. And once we define constructor as private it will also help to stop being inherited. 
Below is the code which defined the Singleton design pattern. Below code is not thread safe.
  1. package com.sdp;  
  2.   
  3. public class SingletonSample {  
  4.   
  5.     private static SingletonSample _instance;  
  6.   
  7.     /// <summary>  
  8.     /// Instance will set only once initially when _insatnce is null  
  9.     /// </summary>  
  10.     public static SingletonSample getInstance() {  
  11.         if(_instance == null){  
  12.             _instance = new SingletonSample();  
  13.         }  
  14.         return _instance;  
  15.     }  
  16.   
  17.     /// <summary>  
  18.     /// To prevent inheritance of this class and to prevent the creation of instance from outside the class  
  19.     /// </summary>  
  20.     private SingletonSample()  
  21.     {  
  22.   
  23.     }  
  24. }  
Below is the code to access singleton instance. To make sure we have single instance, I am accessing the class with Instance 10 times and matching with some refInstance object, along with printing object reference hash code 
  1. package com.sdp;  
  2.   
  3. import java.util.ArrayList;  
  4.   
  5. public class Main {  
  6.   
  7.     public static void main(String[] args) {  
  8.   
  9.        ArrayList<SingletonSample> singletonSamples=new ArrayList<SingletonSample>();  
  10.   
  11.         for(int index=0;index<10;index++){  
  12.          singletonSamples.add((SingletonSample.getInstance()));  
  13.         }  
  14.         SingletonSample refInstance=SingletonSample.getInstance();  
  15.         System.out.println("refInstance object with Hashcode: " + refInstance.hashCode());  
  16.         singletonSamples.forEach(a->{  
  17.             if(a.equals(refInstance)){  
  18.                 System.out.println("Found Same object with Hashcode: " +  a.hashCode());  
  19.             }else {  
  20.                 System.out.println("Found different object with Hashcode: " +  a.hashCode());  
  21.             }  
  22.         });  
  23.     }  
  24. }  
Below is the output snap of the above code
 
 
If we are using the threads in our application and we are expecting to maintain singleton instance even though the class is accessed by threads. In these kinds of cases we need thread safe singleton class.
 
Below is the thread safe code. 
  1. package com.sdp;  
  2.   
  3. public class ThreadSafeSingleton {  
  4.   
  5.     private static ThreadSafeSingleton _instance;  
  6.     public static String Proposal;  
  7.   
  8.     public static ThreadSafeSingleton getInstance(String proposal)  
  9.     {  
  10.         //synchronized keyword which will be used to synchronize threads  
  11.         synchronized  (ThreadSafeSingleton.class)  
  12.         {  
  13.             if (_instance == null)  
  14.             {  
  15.                 Proposal = proposal;  
  16.                 _instance = new ThreadSafeSingleton();  
  17.             }  
  18.         }  
  19.         return _instance;  
  20.     }  
  21.   
  22.     private ThreadSafeSingleton()  
  23.     {  
  24.   
  25.     }  
  26.   
  27.     public void printPraposalName() { 
  28.          System.out.println(Proposal + " proposed to create instance");
  29.     }  
  30. }  
In thread safe code we can see that we are using synchronized keyword which will be used to synchronize threads. If multiple threads try to access the instance of class, the first will acquire synchronized and will proceed next, while the rest will wait until the first thread finishes its execution in that class. And again when second thread, third thread so on move one by one synchronously and as first thread already created instance, the rest of the threads will use the same instance for further execution.
 
To test the above threadsafe singleton code we will ceate a sample thread class and we will use it  in main class. Below is the sample class which extends Thread class 
  1. package com.sdp;  
  2.   
  3. public class Sample extends  Thread {  
  4.   
  5.     private String praposal;  
  6.   
  7.     public Sample(String Praposal){  
  8.   
  9.         praposal = Praposal;  
  10.     }  
  11.     public void run()  
  12.     {  
  13.         try  
  14.         {  
  15.             ThreadSafeSingleton threadSafeSingleton = ThreadSafeSingleton.getInstance(praposal);  
  16.             threadSafeSingleton.printPraposalName();  
  17.         }  
  18.         catch (Exception e)  
  19.         {  
  20.             System.out.println ("Exception is caught");  
  21.         }  
  22.     }  
  23. }  
Below is code where we are creating multiple instances in 4 different threads and while creating each instance we are passing thread name. As per above, the explanation class should maintain the proposal of the first thread. 
  1. package com.sdp;  
  2.   
  3. public class Main {  
  4.   
  5.     public static void main(String[] args) {  
  6.   
  7.         Thread threadA=new Sample("threadA");  
  8.         Thread threadB=new Sample("threadB");  
  9.         Thread threadC=new Sample("threadC");  
  10.         Thread threadD=new Sample("threadD");  
  11.   
  12.         threadA.run();  
  13.         threadB.run();  
  14.         threadC.run();  
  15.         threadD.run();  
  16.     }  
  17. }  
Below is the output of Thread Safe Singleton accessing code. In the below output we can see that threadA hit the Thread Safe Singleton code and created instance and the other 3 threads; i.e. thread, threadC, threadD access same instance created by threadA
 
 

Summary

 
In this article we learned how to create singleton instance and where to use it. And also we saw how to implement thread safe singleton instance.


Similar Articles