Singleton lazy vs eager instantiation

前端 未结 5 1489
暗喜
暗喜 2020-12-07 18:51

If a singleton is implemented as follows,

class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 19:46

    For lazy loading singleton instance, I am using as below.

    class Singleton {
    private static Singleton instance;
    private Singleton(){
    
    }
    public static Singleton getInstance() {
        if(null==instance){
            synchronized(Singleton.class){
                if(null==instance){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
    }
    

提交回复
热议问题