Singleton Design Pattern

The Singleton Design pattern is used for the creating a single/ specific no of objects. This pattern comes under Creational design patterns. There are multiple ways to create a singleton design pattern which are covered in this article. The real world example for this pattern is a Database Connection. There will be only one database connection across the web application. This can be achieved with singleton Design Pattern

Multiple ways to create Singleton Class

Eager/Early instantiation : This is done by directly creating object using new operator
Lazy instantiation : This is done by creating object only after checking whether already singleton object is available or NOT.

There are not much differences in these 2 methods. Only the instantiation of the objects differ. Lets Understand Singleton Design Pattern with an example for both eager and lazy instantiation.

Singleton Class with Eager Instantiation

  1. public class MySingleton {
  2. private static MySingleton obj = new MySingleton();
  3. private MySingleton(){}
  4. public static MySingleton getObj(){
  5. return obj;
  6. }
  7. }

Singleton Class with Lazy Instantiation

  1. public class MySingleton {
  2. private static MySingleton obj = null;
  3. private MySingleton(){}
  4. public static MySingleton getObj(){
  5. if(obj == null){
  6. obj = new MySingleton();
  7. }
  8. return obj;
  9. }
  10. }
  11.  
  12. public class MyMain{
  13.  
  14. public static void main(String[] args){
  15. MySingleton obj1 = MySingleton.getObj();
  16. MySingleton obj2 = MySingleton.getObj();
  17. }
  18.  
  19. }

Consider there are 2 Threads running concurrently, if the method getObj() is not synchronized, both might try to access the method at once. This might result in the condition obj == null to true, this will lead to creation of 2 MySingleton instances. To over come this in lazy instantiation. In the above sample for Singleton Classes, it is not Thread Safe.

  1. if(obj == null) {
  2. obj = new MySingleton();
  3. }
  1. public class MySingleton {
  2. private static MySingleton obj 1= null;
  3. private MySingleton(){}
  4. public static synchronized MySingleton getObj(){
  5. if(obj == null){
  6. obj = new MySingleton();
  7. }
  8. return obj;
  9. }
  10. }

In the above lazy instantiation , we use synchronized for getObj() method. Thus it makes it thread safe. It allows only one thread to access the resource at a time. These are the basics of Singleton Design Pattern.

LEAVE A REPLY

Please enter your comment!
Please enter your name here