zoukankan      html  css  js  c++  java
  • 如何正确地写出单例模式

    懒汉式,线程不安全

    public class Singleton {
    private static Singleton instance;
    private Singleton (){}

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

    懒汉式,线程安全

    public class Singleton {
    private static Singleton instance;
    private Singleton (){}

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

    双重检验锁

    public static Singleton getSingleton() {
    if (instance == null) { //Single Checked
    synchronized (Singleton.class) {
    if (instance == null) { //Double Checked
    instance = new Singleton();
    }
    }
    }
    return instance ;
    }

    这段代码看起来很完美,很可惜,它是有问题。主要在于instance = new Singleton()这句,这并非是一个原子操作,事实上在 JVM 中这句话大概做了下面 3 件事情。

    1. 给 instance 分配内存
    2. 调用 Singleton 的构造函数来初始化成员变量
    3. 将instance对象指向分配的内存空间(执行完这步 instance 就为非 null 了)

    但是在 JVM 的即时编译器中存在指令重排序的优化。也就是说上面的第二步和第三步的顺序是不能保证的,最终的执行顺序可能是 1-2-3 也可能是 1-3-2。如果是后者,则在 3 执行完毕、2 未执行之前,被线程二抢占了,这时 instance 已经是非 null 了(但却没有初始化),所以线程二会直接返回 instance,然后使用,然后顺理成章地报错。

    我们只需要将 instance 变量声明成 volatile 就可以了。

    public class Singleton {
    private volatile static Singleton instance; //声明成 volatile
    private Singleton (){}

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

    }

    饿汉式 static final field

    public class Singleton{
    //类加载时就初始化
    private static final Singleton instance = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
    return instance;
    }
    }


    静态内部类 static nested class

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


    枚举 Enum

    public enum EasySingleton{
    INSTANCE;
    }
     


     
  • 相关阅读:
    一起talk C栗子吧(第九十回:C语言实例--使用管道进行进程间通信三)
    集群技术(三)MySQL集群深度解析
    ZOJ 3609 Modular Inverse(扩展欧几里德)
    8,16小感
    Dagger2----一个最简单的Dagger2依赖的实现
    android:模拟水波效果的自己定义View
    SQL Server 运行计划操作符具体解释(1)——断言(Assert)
    参数类型 (实体类层)eneity或pojo 常用参数类型
    参数类型 (@Controller层)
    参数类型 (@Service层) impl
  • 原文地址:https://www.cnblogs.com/chdchd/p/13204041.html
Copyright © 2011-2022 走看看