Sobes.tech
Middle

How to create a thread-safe Singleton in Java?

sobes.tech AI

Answer from AI

There are several ways to create a thread-safe Singleton:

  1. Eager Initialization:

    public class Singleton {
        private static final Singleton INSTANCE = new Singleton(); // Created at class loading
    
        private Singleton() {} // Private constructor
    
        public static Singleton getInstance() {
            return INSTANCE;
        }
    }
    

    Simple and thread-safe, but the object is created even if it is not used.

  2. Lazy Initialization with synchronized method:

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

    Safe, but may be inefficient due to excessive synchronization on each call.

  3. Lazy Initialization with Double Checked Locking:

    public class Singleton {
        private static volatile Singleton instance; // Using volatile
    
        private Singleton() {}
    
        public static Singleton getInstance() {
            if (instance == null) { // First null-check (without lock)
                synchronized (Singleton.class) { // Lock
                    if (instance == null) { // Second null-check (inside lock)
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    

    Reduces unnecessary synchronization. Using volatile guarantees correct visibility of the object initialization between threads.

  4. Using Enum:

    public enum Singleton {
        INSTANCE; // Single instance
    
        // Additional methods and fields
        public void doSomething() {
            // ...
        }
    }
    

    The simplest and most reliable way in terms of thread safety and avoiding deserialization issues. Java guarantees that enum constants are initialized only once.