singleton pattern in java. lazy initialization

后端 未结 6 1717
遥遥无期
遥遥无期 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:15

    The second one is thread safe, but it has the overhead of synchronized on every call, no matter if the instance is constructed or not. The first option has one major flaw that it doesn't have a check for if (_instance == null) in the synchronized block to prevent creating two instances.

提交回复
热议问题