Ais*_*war 2 java concurrency multithreading double-checked-locking
我正在查看我们的应用程序中的一些代码,我认为可能会遇到" 双重检查锁定 "的情况.我写了一些与我们的工作类似的示例代码.
任何人都可以看到这是如何经历双重检查锁定?或者这样安全吗?
class Foo {
private Helper helper = null;
public Helper getHelper() {
Helper result;
synchronized(this) {
result = helper;
}
if (helper == null) {
synchronized(this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
}
Run Code Online (Sandbox Code Playgroud)
从wiki借来的基本代码.
这是不必要的复杂,最简单的"安全"做DCL的方式是这样的:
class Foo {
private volatile Helper helper = null;
private final Object mutex = new Object();
public Helper getHelper() {
if (helper == null) {
synchronized(mutex) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
}
Run Code Online (Sandbox Code Playgroud)
这里的关键点是:
this.