单例模式的一种实现方式,但很多人会忽略volatile关键字,因为没有该关键字,程序也可以很好的运行,只不过代码的稳定性总不是100%,说不定在未来的某个时刻,隐藏的bug就出来了。

双重校验锁

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

  懒加载的优雅写法静态内部类

public class Singleton {  

        private Singleton (){}  

  public static Singleton getInstance(){  
        return SingletonHolder.instance;  
    } 
    static class SingletonHolder {  
        static Singleton instance = new Singleton();  
    }  

 

}

 转http://www.jianshu.com/p/195ae7c77afe 

http://cantellow.iteye.com/blog/838473

相关文章:

  • 2021-10-20
  • 2021-06-01
  • 2021-07-07
  • 2022-01-06
  • 2022-02-25
  • 2021-09-28
  • 2021-09-24
猜你喜欢
  • 2021-05-29
  • 2021-12-29
  • 2022-12-23
  • 2021-08-14
  • 2021-08-26
  • 2021-11-30
相关资源
相似解决方案