Search code examples
oopsynchronizationsingletonlazy-initialization

Why do we synchronize lazy singletons but not eager ones?


Typical lazy singleton:

public class Singleton {
    private static Singleton INSTANCE;

    private Singleton() {

    }

    public static synchronized Singleton getInstace() {
        if(INSTANCE == null)
            INSTANCE = new Singleton();

        return INSTANCE;
    }
}

Typical eager singleton:

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

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

Why are we not concerned about synchronization with eager singletons, but have to worry about synchronization with their lazy cousins?


Solution

  • Since an eager singleton is initialized when the class if first loaded into memory (jit) and this happens only once. However if two clients will try to call the singleton instance method from two threads at the same time, two singletons may be created.