Java – private constructors and instances – multiple choice

I try to find the answers to the following questions I tried to find the answer on Google, but people seem to have different answers to this question Someone can explain their answer

public class Gingleton {
    private static Gingleton INSTANCE = null;

    public static Gingleton getInstance()
    {
        if ( INSTANCE == null )
        {
            INSTANCE = new Gingleton();
        }
        return INSTANCE;
    }

    private Gingleton() {
    }
}

>Multiple gingleton instances can be created (my choice) > never create a gingleton > the constructor is private, cannot call > value, can be garbage collected, and can call getInstance to return garbage data

Solution

New instance creation in getInstance () will not be synchronized in any way, so multiple instances may be created in a multithreaded environment To ensure that only one instance should be executed:

public class Gingleton {

    // volatile
    private static volatile Gingleton INSTANCE = null;

    public static Gingleton getInstance()
    {
        if ( INSTANCE == null )
        {
            synchronized (Gingleton.class) {  // Synchronized
                if ( INSTANCE == null )
                {
                    INSTANCE = new Gingleton();
                }
            }
        }
        return INSTANCE;
    }

    private Gingleton() {
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>