Luxoft interview question

Describe how you should write thread-safe singleton with lazy initialization.

Interview Answer

Anonymous

13 Mar 2021

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

1