Mastering the Singleton Design Pattern in Java

Mastering the Singleton Design Pattern in Java


Ensuring that a class has only one instance while providing a global access point is a common requirement in software development. The Singleton Design Pattern solves this by restricting object instantiation, making it ideal for logging, caching, configuration management, and database connections.

Why Use Singleton?

  • Ensures a single instance across the application
  • Reduces memory usage by preventing redundant object creation
  • Provides a global access point to shared resources
  • Ensures thread safety when implemented correctly

Popular Singleton Implementations in Java

  • Eager Initialization (Simple but instance is created at class loading)

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    private Singleton() { }
    public static Singleton getInstance() { return INSTANCE; }
}        

  • Lazy Initialization (Efficient but not thread-safe)

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

  • Thread-Safe Singleton using synchronized

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

  • Double-Checked Locking (Optimal for Performance & Thread Safety)

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

  • Best Practice: Enum Singleton (Thread-safe & Reflection-proof)

public enum Singleton {
    INSTANCE;
    public void show() { System.out.println("Singleton using Enum"); }
}        

When to Use Singleton?

  • Configuration Management
  • Logging Services
  • Caching Mechanisms
  • Database Connection Management

However, avoid Singleton if:

  • Multiple instances are required
  • It creates unnecessary dependencies (tight coupling)
  • It hinders unit testing due to global state


Aqib Javed

VP Backend Eng @ JPMorgan | Ex - Amazonian | Ex - Morgan Stanley | Ex- EPAM

3 周

Helpful and simple to understand, worth looking into another pattern to achieve lazy singleton object with thread safety called "initialization on-demand holder pattern".

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了