Sobes.tech
Junior — Middle

How to implement the Singleton pattern in Java?

sobes.tech AI

Answer from AI

The Singleton pattern in Java guarantees that a class has only one instance and provides a global point of access to it.

One simple and thread-safe way to implement this is by using an enum:

public enum Singleton {
    INSTANCE;

    public void someMethod() {
        // logic
    }
}

Usage:

Singleton.INSTANCE.someMethod();

Another classic way is with lazy initialization and synchronization:

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;
    }
}

This approach ensures that the instance is created only upon the first call and is thread-safe.