🔥 Launch Offer: Interview Preparation Bundle @ ₹2,499 ₹9,999 • 75% OFF. Offer expires in 🔥 Launch Offer: Interview Preparation Bundle @ ₹2,499 ₹9,999 • 75% OFF. Offer expires in Interview Preparation Bundle @ ₹2,499 ₹9,999

00:00:00 Get Bundle
home / practice / thread-safe-singleton
medium Design Patterns

Thread-safe Singleton

Implement a lazy, thread-safe Singleton for a Config object. Interviewers often ask why double-checked locking needs volatile, or why an enum singleton is simpler.

Requirements

  • Only one instance ever.
  • Safe if two threads call getInstance() at the same time.
  • Do not create the instance until first use.

Starter code

public class Config {
    // TODO: private instance + getInstance()

    private Config() {}

    public String env() {
        return "prod";
    }

    public static void main(String[] args) {
        Config a = null; // Config.getInstance();
        Config b = null; // Config.getInstance();
        System.out.println(a == b);
    }
}

Solution

public class Config {
    private static volatile Config instance;

    private Config() {}

    public static Config getInstance() {
        if (instance == null) {
            synchronized (Config.class) {
                if (instance == null) {
                    instance = new Config();
                }
            }
        }
        return instance;
    }

    public String env() {
        return "prod";
    }

    public static void main(String[] args) {
        Config a = Config.getInstance();
        Config b = Config.getInstance();
        System.out.println(a == b); // true
        System.out.println(a.env());
    }
}