创建型-单例

1、饿汉式:

public class Singleton {
  private final static Singleton INSTANCE = new Singleton();
  private Singleton() { }
  public static Singleton getInstance() {
     return INSTANCE;
   }
}

2、懒加载之占位符模式:(推荐)

属于懒汉式单例,因为Java机制规定,内部类SingletonHolder只有在getInstance()方法第一次调用的时候才会被加载(实现了lazy),而且其加载过程是线程安全的。内部类加载的时候实例化一次instance。

public class Singleton {
  private Singleton() { }
  private static class SingletonHolder {
     private final static Singleton INSTANCE = new Singleton();
   }
  public static Singleton getInstance() {
     return SingletonHolder.INSTANCE;
   }
}

 

3、懒加载之普通加锁模式:

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


虽然解决了线程安全问题,但是每个线程调用getInstance都要加锁,我们想要只在第一次调用getInstance时加锁,请看下面的双重检测方案

 

4、懒加载之双重检测模式:(推荐)

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

特别注意这种方式会有指令重排问题(关于指令重排可参考这篇博文),针对instance实例变量用volatile修饰就可以了,volatile修饰的话就可以确保instance= new Singleton();对应的指令不会重排序:

public class Singleton {
  private static volatile Singleton instance = null;  //以volatile关键字修饰防止指令重排
  private Singleton() { }  //构造函数为私有,防止被实例化
  public static Singleton getInstance() {
     if(instance == null) {     //双重检测
        synchronzied(Singleton.class) {
           if(instance == null) {
               instance = new Singleton();
           }
        }
     }
     return instance;
   }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值