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;
    }
     


     
  • 相关阅读:
    前端开发网址
    Iconfot阿里妈妈-css高级应用
    手机端的META你知道多少?
    24个 HTML5 & CSS3 下拉菜单效果及制作教程
    css :clip rect 正确的使用方法
    layui :iframe 与 layer 的位置问题
    时间戳转现实时间的方法
    关于 iframe 的小问题若干
    使用 forever 启动 vue 需要注意的问题
    var 的一个坑,以及 let
  • 原文地址:https://www.cnblogs.com/chdchd/p/13204041.html
Copyright © 2011-2022 走看看