线程安全的单例模式的几种实现方法分享

线程安全的单例模式实现有几种思路,个人认为第2种方案最优雅:饿汉式、借助内部类、普通加锁解决、双重检测,但要注意写法,如果单体模式继续扩展为N元单体模式,那就是对象池模式了。


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) {
            Singleton temp = instance;
            if(temp == null) {
               temp = new Singleton();
               instance = temp
            }
         }
      }
      return instance;
   }
}
由于指令重排序问题,所以不可以直接写成下面这样:
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;
   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、付费专栏及课程。

余额充值