我想在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"声明.
我怎么解决这个问题?
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html上的页面说,双重检查锁定在java中是有缺陷的.我只是想知道它是否也适用于其他语言(C#,Vb,C++等)
我读过双重检查锁定模式:是否破碎?,这是双重检查锁定?,如何解决Java中的"双重检查锁定"声明?说实话,我不知道共同的共识是什么.有人说是的,其他人说不.
无论如何,我的问题是它是否也适用于其他语言(C#,Vb,C++等)