Implementing Thread-Safe Singleton Patterns in Java

Singleton pattern ensures only one instance of a class exists during runtime.

Lazy vs Eager Initialization

  1. Lazy Initialization: Instance created only when first requested
public class LazySingleton {
    private LazySingleton() {}
    private static LazySingleton instance = null;
    
    public static LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}
  1. Eager Initialization: Instance created at class loading
public class EagerSingleton {
    private static final EagerSingleton instance = new EagerSingleton();
    private EagerSingleton() {}
    
    public static EagerSingleton getInstance() {
        return instance;
    }
}

Thread Safety Considerations

The basic lazy implementation isn't thread-safe. Multiple threads might create separate instnaces.

Thread-Safe Implmeentations

  1. Eager Initialization: Naturally thread-safe as instance is created during class loading
  2. Synchronized Method:
public class SyncSingleton {
    private static SyncSingleton instance;
    private SyncSingleton() {}
    
    public static synchronized SyncSingleton getInstance() {
        if (instance == null) {
            instance = new SyncSingleton();
        }
        return instance;
    }
}
  1. Double-Checked Locking:
public class DCLSingleton {
    private static volatile DCLSingleton instance;
    private DCLSingleton() {}
    
    public static DCLSingleton getInstance() {
        if (instance == null) {
            synchronized (DCLSingleton.class) {
                if (instance == null) {
                    instance = new DCLSingleton();
                }
            }
        }
        return instance;
    }
}

Tags: java Design Patterns singleton Thread Safety multithreading

Posted on Sun, 10 May 2026 02:41:43 +0000 by Avendium