singleton pattern in java. lazy initialization

后端 未结 6 1754
遥遥无期
遥遥无期 2020-12-28 11:02
public static MySingleton getInstance() {
 if (_instance==null) {
   synchronized (MySingleton.class) {
      _instance = new MySingleton();
   }
 }
 return _instanc         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-28 11:38

    I would suggest the following implementation

    public class MySingleTon
    {
    
      private static MySingleton obj;
    
      //private Constructor
      private MySingleTon()
      {
      }
    
    
      public static MySingleTon getInstance()
      {
         if(obj==null)
         {
            synchronized(MySingleTon.class)
            {
             if(obj == null)
             {
                 obj = new MySingleTon();
             }
            }
         }
         return obj;    
      }
    }
    

提交回复
热议问题