Sobes.tech
Junior — Middle

How does the Singleton pattern implementation consider multithreading features?

sobes.tech AI

Answer from AI

When implementing the Singleton pattern in a multithreaded environment, it is important to ensure that only one instance of the class is created at the same time. Various approaches are used:

  • Synchronization (synchronized): the method of obtaining the instance is locked so that only one thread can create the object.

  • Double-checked locking: first, it checks whether the instance has been created without locking, then inside the synchronized block, the instance is created if it has not been created yet.

  • Using volatile: the instance variable is declared volatile to avoid issues with caching and instruction reordering.

  • Initialization-on-demand holder idiom: a nested static class contains the instance, which is created upon the first access, ensuring thread safety without synchronization.

Example with double-checked locking in Java:

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;
    }
}