I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can i
Query 1:
Different ways of creating Singleton
Normal Singleton
: static initialization Lazy Singleton
: Double locking Singleton & : Initialization-on-demand_holder_idiom singletonHave a look at below code:
public final class Singleton{
private static final Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public enum EnumSingleton {
INSTANCE;
}
public static void main(String args[]){
System.out.println("Singleton:"+Singleton.getInstance());
System.out.println("Enum.."+EnumSingleton.INSTANCE);
System.out.println("Lazy.."+LazySingleton.getInstance());
}
}
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
}
Related SE questions:
What is an efficient way to implement a singleton pattern in Java?
Query 2:
One Singleton instance is created per ClassLoader
. If you want to avoid creation of Singleton
object during Serializaiton
, override below method and return same instance.
private Object readResolve() {
return instance;
}
Query 3:
To achieve a cluster level Singleton
among multiple servers, store this Singleton object in a distributed caches like Terracotta
, Coherence
etc.