在Java中如何写一个正确的单例模式?

饿汉式写法

//饿汉式写法
public class Singleton{
  private static Singleton singleton = new Singleton();
  
  private Singleton(){}
  
  public static Singleton getInstance(){
    return singleton;
  } 
}

//静态代码块写法
public class Singleton{
  private static Singleton singleton;
  
  static {
    singleton = new Singleton()
  }
  
  private Singleton(){}
  
  public static Singleton getInstance(){
    return singleton;
  } 
}

懒汉式写法

//只能在单线程上使用,在多线程不能使用该方式
public class Singleton{
  private static Singleton singleton;
  
  private Singleton(){}
  
  public static Singleton getInstance(){
    if (singleton == null) {
      singleton = new Singleton();
    }
    return singleton;
  } 
}
//线程安全的写法,缺点:效率太低了。
public class Singleton{
  private static Singleton singleton;
  
  private Singleton(){}
  
  //在该方法上添加synchronized关键字
  public static synchronized Singleton getInstance(){
    if (singleton == null) {
      singleton = new Singleton();
    }
    return singleton;
  } 
}
//双重检查模式,不仅线程安全,而且效率快。
public class Singleton{
  private static volatile Singleton singleton;
  
  private Singleton(){}
  
  public static synchronized Singleton getInstance(){
    if (singleton == null) {
      synchronized (Singleton.class) {
        if (singleton == null) {
          singleton = new Singleton();
        }
      }
    }
    return singleton;
  } 
}

为什么要double-check?去掉第二个行不行

有两个线程同时调用,成功判断singleton == null,会有一个线程先进入同步语句。并进入第二层if判断,第二个线程进行等待,不过当第一个线程执行完new Singleton()语句后,第二个线程开始运行,如果没有第二层if判断,则会创建第二个实例;第一个if也不能去掉,如果去掉所有的线程都会串行执行,效率低下。

为什么要在private static volatile Singleton singleton添加volatile,因为singleton = new Singleton();并非是一个原子操作,在JVM中这句语句至少做了3件事,存在重排序的问题,
在这里插入图片描述

借助jdk1.5中添加的枚举类来实现单例模式

不仅能避免多线程同步的问题,还能防止反序列化和反射创建新的对象来破坏单例的情况出现

public enum Singleton {
    INSTANCE;

    public void whatever() {
        System.out.println("执行了单例类的方法,例如返回环境变量信息");
    }
    public static void main(String[] args) {
        //演示如何使用枚举写法的单例类
        Singleton.INSTANCE.whatever();
    }
}

总结:推荐使用枚举类来实现单例模式

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值