A
A
angry_cellophane2014-04-13 22:56:46
Java
angry_cellophane, 2014-04-13 22:56:46

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");
    }
}

Output:
1
2
instance created
3

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artyushov, 2014-04-14
@angry_cellophane

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.

S
Sergey, 2014-04-14
Protko @Fesor

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.

A
Alexander Fedotov, 2014-04-18
@fealsoft

For example, adding a method to the class

public static void test() {
            System.out.println("test");
        }

and calling it
System.out.println("1");
        Singleton instance1 = null;
        instance1.test();
        System.out.println("2");
        Singleton instance2 = Singleton.getInstance();
        System.out.println("3");

1
instance created
test
2
3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question