爲什麼這裏需要局部變量我不明白: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