用双端检锁机制不能保证线程安全的原因是什么?

用双端检锁机制不能保证线程安全,原因是存在指令重排。


/**
 * @program: mybatis
 * @description:
 * @author: Miller.FAN
 * @create: 2019-11-11 17:49
 **/
public class SingletonDome {

    private static SingletonDome instance = null;
    private SingletonDome() {
        System.out.println(Thread.currentThread().getName() + "/t 我是构造方法SingletonDome");
    }

    //DLC 双端检锁机制
    public static SingletonDome getInstance() {
        if(instance == null) {
            synchronized (SingletonDome.class) {
                if(instance == null) {
                    instance =  new SingletonDome();
                }
            }
        }
        return instance;
    }
    public static void main(String[] args) {
        for (int i = 0; i < 10 ; i++) {
            new Thread( () -> {
                SingletonDome.getInstance();
            },String.valueOf(i)).start();
        }
    }
}

2、优化手段

/**
 * @program: mybatis
 * @description:
 * @author: Miller.FAN
 * @create: 2019-11-11 17:49
 **/
public class SingletonDome {
    //加volatile,禁止指令重排
    private static volatile SingletonDome instance = null;
    private SingletonDome() {
        System.out.println(Thread.currentThread().getName() + "/t 我是构造方法SingletonDome");
    }

    //DLC 双端检锁机制
    public static SingletonDome getInstance() {
        if(instance == null) {
            synchronized (SingletonDome.class) {
                if(instance == null) {
                    instance =  new SingletonDome();
                }
            }
        }
        return instance;
    }
    public static void main(String[] args) {
        for (int i = 0; i < 10 ; i++) {
            new Thread( () -> {
                SingletonDome.getInstance();
            },String.valueOf(i)).start();
        }
    }
}
发布了85 篇原创文章 · 获赞 21 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41670928/article/details/103014645
今日推荐