Sobes.tech
Junior — Middle

How to ensure safe access to a singleton class in a multithreaded environment?

sobes.tech AI

Answer from AI

To ensure safe access to a singleton class instance in a multithreaded environment in Java, several approaches can be used:

  1. Synchronized getInstance() method — a simple way, but may lead to performance reduction due to locking on each call:
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. Double-checked locking — reduces synchronization overhead:
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;
    }
}
  1. Using a static nested class — lazy initialization and thread safety guaranteed by JVM:
public class Singleton {
    private Singleton() {}

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

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

This method is considered the most efficient and simple.

  1. Enum Singleton — the simplest and safest way, guaranteeing thread safety and serialization protection:
public enum Singleton {
    INSTANCE;

    // methods
}

The choice of approach depends on performance requirements and implementation convenience.

How to ensure safe access to a singleton class in a… - sobes.tech