Java.Multithreading.How to create a thread-safe Singleton?

🔐 Creating a thread-safe Singleton is a classic Java interview topic — and a crucial design skill. Let’s explore 5 solid ways to create a thread-safe singleton, ranked by safety, readability, and performance.

public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {                     // First check
            synchronized (Singleton.class) {
                if (instance == null) {             // Second check
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

✅ Pros:

  • Thread-safe ✅
  • Lazy initialization ✅
  • Fast after first initialization ✅

✅ 2. Static Inner Class — Best Combo: Lazy + Thread-safe + Clean

public class Singleton {
    private Singleton() {}

    private static class Holder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return Holder.INSTANCE;
    }
}

🧠 How it works:

  • Holder is not loaded until getInstance() is called.
  • The JVM guarantees thread safety during class loading.

✅ Pros:

  • No synchronization overhead
  • Lazy loaded
  • Thread-safe by JVM spec

✅ 3. Eager Initialization — Thread-safe but not Lazy

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

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

✅ Pros:

  • Thread-safe by default
  • Simple and clean

❌ Cons:

  • Instance is created even if never used (not lazy)

✅ 4. Enum Singleton — Bulletproof 🚀

public enum Singleton {
    INSTANCE;

    public void doSomething() {
        System.out.println("Doing something...");
    }
}

✅ Pros:

  • Thread-safe
  • Lazy-loaded by JVM
  • Protects against reflection & serialization attacks

💡 Tip: This is Effective Java’s recommended way (Joshua Bloch).

✅ 5. Using synchronized Method — Easy but Slower

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

❌ Cons:

  • Thread-safe, but slower due to full method synchronization

🧠 Summary Table

MethodThread-safeLazyFastRecommended?
Double-Checked Locking
Static Inner Class✅✅✅
Eager Initialization⚠️ If size isn’t a concern
Enum Singleton✅✅✅✅✅✅ (most robust)
Synchronized Method🚫 Use only for learning
This entry was posted in Без рубрики. Bookmark the permalink.