So I know that the singleton pattern is implemented like this:
public class ClassName {
private static ClassName instance;
public static ClassName getInstance() {
if (instance == null) {
instance = new ClassName();
}
return instance;
}
private ClassName() {}
}
What I want to ask is why you couldn't just do it like this:
public class ClassName {
public static final ClassName instance = new ClassName();
private ClassName() {}
}
Way fewer lines of code and seems to do exactly the same thing. Minus the lazy initialization of course, but I don't see why lazy initialization would be a significant benefit anyway. I'm not very experienced and would appreciate if you would enlighten me with your knowledge, thanks.
Initializing the singleton instance inline and letting the classloader worry about synchronization may not be an extremely common practice, but it's definitely not unheard of.
The common idiom, however, is to have the instance variable private and return it through a getter so that no other code depends on it directly. That way, if in the future you decide you want something fancier (like, e.g., lazy initialization you mentioned), you can easily refactor your code without breaking the API:
public class ClassName {
private static final ClassName instance = new ClassName();
public static ClassName getInstance() {
return instance;
}
private ClassName() {}
}
Your first code use lazy creation with the synchronized
keyword. instance = new ClassName()
the problem with these kind of code is that the instance
var could became non-null before the construction of the singleton and can be interpret in pseudo-code, that the JRE do for create the instance :
mem = allocate() ;
instance = mem ;
ctorSingleton(instance)
So if multiple threads access the method getInstance in same time, is it possible you get a new instance, because in java you have 2 instructions and the pseudo-code that the JRE interpret do it in 3.
I consider your second implement is the good one, because you are the sure it will work fine, and Thread or synchronisation problem are hard to fix.
This come from french article : http://christophej.developpez.com/tutoriel/java/singleton/multithread/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With