Answer the question
In order to leave comments, you need to log in
How to implement a singleton in Java?
All good.
The topic is beaten up and the answer is widely known to many ( once an article , two articles ), but I will put the question as follows: why is it recommended to use the On Demand Holder implementation, and not the usual one through the static getInstance() method, which returns the value of a static field?
The instance will be created at the moment the class is initialized, i.e. the first time the static getInstance method is called (as the JLS says ). Why then is this option discarded and not considered lazy?
And, not to be unfounded, an example:
public class Main {
static class Singleton {
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance(){
return INSTANCE;
}
private Singleton(){
System.out.println("instance created");
}
}
public static void main(String[] args) {
System.out.println("1");
Singleton instance1 = null;
System.out.println("2");
Singleton instance2 = Singleton.getInstance();
System.out.println("3");
}
}
Answer the question
In order to leave comments, you need to log in
Perhaps the point is that in the second case, instance is not created when the getInstance() method is called, but when the class is loaded into the virtual machine. That is, if you somehow refer to this class not in order to get an instance, then it will still be created.
the second article you cited describes why, what and when is best. + in the comments, moments are briefly touched upon when you should not use singleton at all.
For example, adding a method to the class
public static void test() {
System.out.println("test");
}
System.out.println("1");
Singleton instance1 = null;
instance1.test();
System.out.println("2");
Singleton instance2 = Singleton.getInstance();
System.out.println("3");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question