Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as
public class Singleton {
private static Singleton re
This is because your solution is not threadsafe.
The modern way is to tie the instance to an enum value:
enum Singleton {
INSTANCE;
}
If you want to use lazy init of the instance then you can use the ClassLoader to guarantee thread safety:
public class Singleton {
private Singleton() { }
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
More information on Wikipedia