这个问题在某种程度上有所延续和扩展,正如我认为完美的问题:How does assigning to a local variable help here?
这个问题基于Effective Java的第71项,建议通过引入局部变量来提高性能,以实现易失性字段访问:
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; }
@H_404_10@所以,我的问题更常见:
我们应该始终通过将其值分配给局部变量来访问volatile字段吗? (为了存档最佳性能).
即一些成语:
>我们有一些volatile字段,称之为volatileField;
>如果我们想在多线程方法中读取它的值,我们应该:>创建相同类型的局部变量:localVolatileVariable
>赋值volatile字段的值:localVolatileVariable = volatileField
>从本地副本中读取值,例如:if (localVolatileVariable != null) { ... }
@H_404_10@
最佳答案