I have 2 options:
Singleton Pattern
class Singleton{
private static Singleton singleton = null;
public static synchronized Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
using a static final
field
private static final Singleton singleton = new Singleton();
public static Singleton getSingleton() {
return singleton;
}
Whats the difference? (singlethreaded or multithreaded)
Updates: I am aware of Bill Pugh or enum
method.
I am not looking for the correct way, but I have only used 1. Is there really any difference b/w 1 or 2?
The main difference is that with the first option , the singleton will only be initialised when getInstance
is called, whereas with the second option, it will get initialized as soon as the containing class is loaded.
A third (preferred) option which is lazy and thread safe is to use an enum:
public enum Singleton {
INSTANCE;
}
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