Reputation: 3898
Assuming I have an empty constructor for a single ton class , which of the below 2 approaches is better to return an instance from a public getInstance method?
Class level initialization {
public class ClassName{
private static ClassName instance = new ClassName ();
}
}
Lazy loading with double check lock
if (null == instance) {
synchronized (this) {
if(null == instance) {
instance = new className();
}
}
}
I was thinking Class level initialization wouldn't create any harm here. But would like to confirm it from the experts. Please help
Upvotes: 1
Views: 231
Reputation: 533530
You should have a private constructor and a final
instance field. Ideally the class should be final
as well. The simplest way to do all this is to use an enum
public enum Singleton implements MyInterface {
INSTANCE;
}
Upvotes: 1