What is the best/correct way to create a singleton class in java?
One of the implementation I found is using a private constructor and a getInstance() method.
<I will implement singleton in below way.
From Singleton_pattern described by wikiepdia by using Initialization-on-demand holder idiom
This solution is thread-safe without requiring special language constructs (i.e. volatile
or synchronized
public final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}