Sobes.tech
Junior — Middle

What approaches can be used instead of the synchronized keyword to implement the Singleton pattern in a multithreaded environment?

sobes.tech AI

Answer from AI

Instead of using the 'synchronized' keyword to implement Singleton in a multithreaded environment, you can use the following approaches:

  1. Initialization-on-demand holder idiom (static inner class)

    This method uses lazy initialization and guarantees thread safety without synchronization.

    public class Singleton {
        private Singleton() {}
    
        private static class Holder {
            private static final Singleton INSTANCE = new Singleton();
        }
    
        public static Singleton getInstance() {
            return Holder.INSTANCE;
        }
    }
    
  2. Using enum

    Enum in Java guarantees a single instance and thread safety by default.

    public enum Singleton {
        INSTANCE;
    
        public void someMethod() {
            // ...
        }
    }
    
  3. Double-checked locking with volatile

    Allows avoiding full synchronization on each call, synchronizing only during the first creation of the instance.

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

Each of these approaches provides thread safety without constantly using 'synchronized' on the 'getInstance()' method.

What approaches can be used instead of the… - sobes.tech