相关疑难解决方法(0)

如何解决Java中的"双重检查锁定"声明?

我想在Java中实现多线程的延迟初始化.
我有一些类似的代码:

class Foo {
    private Helper helper = null;
    public Helper getHelper() {
        if (helper == null) {
            Helper h;
            synchronized(this) {
                h = helper;
                if (h == null) 
                    synchronized (this) {
                        h = new Helper();
                    } // release inner synchronization lock
                helper = h;
            } 
        }    
        return helper;
    }
    // other functions and members...
}
Run Code Online (Sandbox Code Playgroud)

而且我得到了"Double-Checked Locking is Broken"声明.
我怎么解决这个问题?

java concurrency multithreading locking lazy-loading

33
推荐指数
3
解决办法
2万
查看次数