gpt4 book ai didi

java - 为什么在进行双重检查锁定时将 volatile 字段复制到局部变量

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:34 27 4
gpt4 key购买 nike

我正在阅读 Effective Java 中有关双重检查锁定的内容。该代码执行以下操作:

private volatile FieldType field;  
FieldType getField() {
FieldType result = field;
if (result == null) { // First check (no locking)
synchronized(this) {
result = field;
if (result == null) // Second check (with locking)
field = result = computeFieldValue();
}
}
return result;
}

它说使用 result 似乎是不必要的,但实际上确保 field 在已经初始化的常见情况下只被读取一次。

但是我不明白这一点。和直接做 if(field == null) 有什么区别?我不明白为什么 if (result == null) 不同,更不用说更好了。

最佳答案

解释在下一页(我强调):

What this variable does is to ensure that field is read only once in the common case where it’s already initialized. While not strictly necessary, this may improve performance and is more elegant by the standards applied to low-level concurrent programming. On my machine, the method above is about 25 percent faster than the obvious version without a local variable.

供引用,引用来自p。项目 71 的 284:在 Effective Java 第 2 版中明智地使用惰性初始化

更新:读取本地变量与读取可变变量的区别在于前者可能优化得更好。 volatile 变量不能存储在寄存器或缓存中,也不能对它们进行重新排序的内存操作。此外,读取 volatile 变量可能会触发不同线程之间的内存同步。

有关更多详细信息,请参阅 Java 并发实践,第 3.1.4 节: volatile 变量

关于java - 为什么在进行双重检查锁定时将 volatile 字段复制到局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10512782/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com