githubEdit

Singleton

Purpose: Ensure a class has only one instance and provide a global access point to it

When to Use

✅ Database connection pool ✅ Configuration manager ✅ Logging service ✅ Cache manager

❌ Don't overuse - makes testing difficult (use dependency injection instead)

Implementation

Basic Singleton (Not Thread-Safe)

public class Singleton {
    private static Singleton instance;
    
    private Singleton() {
        // Private constructor prevents instantiation
    }
    
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Problem: Not thread-safe! Two threads can create two instances.


Thread-Safe Singleton (Double-Checked Locking)

Key: volatile ensures visibility across threads, double-check reduces lock overhead.


Enum Singleton (Best in Java)

Why best: Thread-safe by JVM, prevents reflection attacks, serialization-safe.


Real-World Example: Database Connection Pool

Class Diagram

spinner

Pros & Cons

Pros:

  • ✅ Controlled access to single instance

  • ✅ Reduced memory (one instance)

  • ✅ Global access point

Cons:

  • ❌ Violates Single Responsibility (manages own lifecycle + business logic)

  • ❌ Difficult to unit test (global state)

  • ❌ Can hide dependencies (not obvious from constructor)


Alternative: Dependency Injection

Instead of Singleton, prefer DI:


Interview Tips

Q: "Why use Singleton?"

  • A: "Ensure single instance (e.g., config manager). But I'd prefer DI for testability."

Q: "Is your Singleton thread-safe?"

  • A: "Yes, using double-checked locking with volatile keyword"

Last updated