Design Pattern in Java – Singleton

Spread the love

It is a design pattern in which there would be only instance of the class which would be available in the JVM memory.

Since only a single instance of the object would be available in JVM, there need to be some restrictions initially which are below.

1)There would be a default constructor for that class which would be private. So that instantiation of the object is not possible.

2)Declare the private static variable of the same class that is the only instance of the class.

3)Create a public method which returns the static instance of the class everytime when it is called.

There are many ways in which we can implement this in Java.

Let us look at the approach in which we would use a synchronized method i.e; a thread safe implementation for the same.

package com.dpsamples.patterns;

public class SingletonExample {

    //Declare instance as private static
    private static SingletonExample singleInstance;

    //Private Constructor
    private SingletonExample(){
    }
    
    //Method to return singleton instance
    public static synchronized SingletonExample getInstance(){
        if(singleInstance == null){ //Line 9
            singleInstance = new SingletonExample(); //Line 10
        }
        return singleInstance;
    }
    
}

As you see above, we use a synchronized method to return the instance of the Class. If synchronized was not used, then the method would not have been thread safe.

Why? Check Line 9. If two threads one after another would have executed the line initially it would had got null. So 2 instances would have been created in the memory.

That is the importance of the synchronized keyword.