ODNYX.

Singleton Design Pattern

Video Tutorial Coming Soon — Channel Production Underway

The Singleton pattern guarantees that a class has only one instance for the entire lifetime of the application, and provides one global access point to it.

Tip: reach for Singleton when you need exactly one shared object — like a configuration manager, a connection pool, or a logger — and creating multiple instances would cause bugs or waste resources.

The structure

Singleton pattern class diagram showing a Singleton class with a private static instance field and a public static getInstance method returning the same shared instance

The Singleton class exposes one static access point; every caller receives a reference to the same instance.

The class keeps a reference to its own single instance in a private static field, hides its constructor so nobody else can create new instances directly, and exposes one public static method that hands out that shared instance.

Implementing it in Java

public class Singleton {
    private static Singleton instance;

    // Private constructor — nothing outside this class can call `new Singleton()`
    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
Singleton a = Singleton.getInstance();
Singleton b = Singleton.getInstance();

System.out.println(a == b); // true — both variables point to the exact same object

A word of caution

The basic version above isn’t thread-safe — two threads calling getInstance() at the same time could both see instance == null and create two separate objects. Production code typically guards against this with synchronization or by initializing the instance eagerly. We’ll cover thread-safe variations in a later lesson.

What’s next

Next up: the Factory pattern, another creational pattern that solves a different problem — delegating which class gets instantiated, rather than how many instances exist.

Try It Yourself

Challenge 1: Make the Singleton example thread-safe using the double-checked locking pattern.

Show solution

Use synchronized only around the object-creation step, guarded by a second null-check inside the lock:

public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

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

The volatile keyword and the double null-check together prevent two threads from both creating an instance, while avoiding the cost of synchronizing on every call.

📋 Creational Patterns Interview Questions