使用双锁时使单例实例易变的重点是什么? [英] What is the point of making the singleton instance volatile while using double lock?

查看:149
本文介绍了使用双锁时使单例实例易变的重点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private volatile static Singleton uniqueInstance

在单身时使用双锁方法进行同步为什么单个实例声明为volatile?我可以在不将其声明为volatile的情况下实现相同的功能吗?

In a singleton when using double lock method for synchronization why is the single instance declared as volatile ? Can I achieve the same functionality without declaring it as volatile ?

推荐答案

没有 volatile 代码在多个线程中无法正常工作。

Without volatile the code doesn't work correctly with multiple threads.

来自维基百科的双重检查锁定


从J2SE 5.0开始,此问题已修复。 volatile关键字现在可确保多个线程正确处理单例实例。这个新的成语在双重检查锁定已损坏声明中有所描述



// Works with acquire/release semantics for volatile
// Broken under Java 1.4 and earlier semantics for volatile
class Foo {
    private volatile Helper helper = null;
    public Helper getHelper() {
        Helper result = helper;
        if (result == null) {
            synchronized(this) {
                result = helper;
                if (result == null) {
                    helper = result = new Helper();
                }
            }
        }
        return result;
    }

    // other functions and members...
}

一般情况下,如果可能的话,你应该避免重复检查锁定,因为很难做到正确,如果你弄错了,很难找到错误。请尝试这种更简单的方法:

In general you should avoid double-check locking if possible, as it is difficult to get right and if you get it wrong it can be difficult to find the error. Try this simpler approach instead:


如果辅助对象是静态的(每个类加载器一个),则另一种选择是初始化按需持有人习惯用语



// Correct lazy initialization in Java 
@ThreadSafe
class Foo {
    private static class HelperHolder {
       public static Helper helper = new Helper();
    }

    public static Helper getHelper() {
        return HelperHolder.helper;
    }
}

这篇关于使用双锁时使单例实例易变的重点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆