为什么这里需要局部变量我不明白:https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java 我们能有什么问题,如果我们没有这样的:的Java懒线与最终的现场实施安全单
public class FinalWrapper<T> {
public final T value;
public FinalWrapper(T value) {
this.value = value;
}
}
public class Foo {
private FinalWrapper<Helper> helperWrapper;
public Helper getHelper() {
FinalWrapper<Helper> tempWrapper = helperWrapper;
if (tempWrapper == null) {
synchronized(this) {
if (helperWrapper == null) {
helperWrapper = new FinalWrapper<Helper>(new Helper());
}
tempWrapper = helperWrapper;
}
}
return tempWrapper.value;
}
}
我从得到这个代码局部变量?根据维基文章撰写:Semantics of final field in Java 5 can be employed to safely publish the helper object without using volatile. The local variable tempWrapper is required for correctness: simply using helperWrapper for both null checks and the return statement could fail due to read reordering allowed under the Java Memory Model. Performance of this implementation is not necessarily better than the volatile implementation.
在此先感谢。
您是使用嵌套的私有类,它通过类加载机制强制执行单行为的懒惰持有者成语更好。 –
我已在下面更新了我的答案,以提供有关重新排序的更多信息。我希望它耗尽了这个话题。 – cbartosiak