All 15 Design Patterns in Java questions
More in Design Patterns in Java
Advertisement
Back to results for “OOP & Classes”
Java › Design Patterns in Java

What is the Singleton pattern, and how would you implement a thread-safe Singleton in Java?

Beginner

Answer

Singleton ensures a class has exactly one instance and provides a global access point to it -- the enum-based approach is generally considered the simplest, safest way to implement it in Java (inherently thread-safe, serialization-safe, and immune to reflection-based instantiation attacks that can break other approaches), though the classic double-checked-locking lazy initialization pattern (using a volatile field) remains common for scenarios not suited to enum.
public enum ConfigManager {
    INSTANCE;

    private final Map<String, String> settings = new HashMap<>();

    public String get(String key) { return settings.get(key); }
}

// Usage
ConfigManager.INSTANCE.get("apiUrl");
Real-world example An application-wide configuration manager is implemented as an enum-based Singleton, guaranteeing exactly one instance exists across the entire application regardless of how many places reference ConfigManager.INSTANCE, with the JVM itself enforcing this guarantee rather than relying on manual synchronization logic.

Common follow-ups: Why is the enum-based Singleton considered immune to reflection-based attacks that can break the classic private-constructor approach?;What are the criticisms of Singleton as an anti-pattern, particularly regarding testability?