What is the way to implement a thread-safe Singleton design pattern in Java?

In Java there are many options to implement a thread-safe Singleton pattern. Some of these are as follows:

  • Double Checked Locking: This is the most popular method to implement Singleton in Java. It is based on Lazy Initialization. In this we first check the criteria for locking before acquiring a lock to create an object. In Java we use it with volatile keyword.Sample code:

    class DoubleCheckSingleton {
    private volatile HelloSingleton helloSingleton; // Use Volatile

    public HelloSingleton getHelloSingleton() {
    HelloSingleton result = helloSingleton;
    if (result == null) {
    synchronized(this) { // Synchronize for thread safety
    result = helloSingleton;
    if (result == null) {
    result = new HelloSingleton();
    helloSingleton = result;
    }
    }
    }
    return result;
    }

    }

  • Bill Pugh Singleton: We can also use the method by Bill Pugh for implementing Singleton in Java. In this we use an Inner Static class to create the Singleton instance.Sample code:

    public class SingletonBillPugh {

    // Inner class that holds instance
    private static class InnerSingleton{
    private static final SingletonBillPugh INSTANCE = new SingletonBillPugh();
    }

    // Private constructor
    private SingletonBillPugh(){}

    public static SingletonBillPugh getInstance(){
    return InnerSingleton.INSTANCE;
    }
    }

    When first time SingletonBillPugh is loaded in memory, InnerSingleton is not loaded. Only when getInstance() method is called, InnerSingleton class is loaded and an Instance is created.

  • Enum: We can also use Java enum to create thread-safe implementation. Java enum values are accessible globally so these can be used as a Singleton.Sample Code:

    public enum SingletonEnum {

    INSTANCE;

    public static void doImplementation(){
    …..
    }
    }

Read the full book at www.amazon.com
Posted in Design Pattern, Design Pattern Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *

*