如何分配到局部变量帮助这里? [英] How does assigning to a local variable help here?

查看:195
本文介绍了如何分配到局部变量帮助这里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读有关 Effective Java 的双重锁定。

该代码执行以下操作:

I am reading about double check locking from Effective Java.
The code does the following:

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 似乎不需要,但实际上确保字段在其已经初始化的常见情况下仅读取一次。

但是我不理解这一点。

与执行 if(field == null)有什么区别?

我不会为什么 if(result == null)是不同的,更不用说更好。

任何帮助理解这个?

It says that using result seems unneeded but actually ensures that the field is only read only once in the common case where it is already initialized.
But I don't understand this.
What is the difference with doing if(field == null) directly?
I don't get why if (result == null) is different, let alone better as stated.
Any help understanding this please?

推荐答案

在这个例子中的想法是,结果/字段将被使用一次以上进一步下来我猜。访问结果更便宜(不易变动)。

The thinking in that example is that result/field will be used more than once further down I guess. Accessing result is cheaper (it's not volatile).

如果需要这样做,请使用需求持有者模式上的初始化。
http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

Use the initializaton on demand holder pattern instead if you need to do this. http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

将一些我的澄清添加到回答本身的好处... clear:

Adding some of my clarifications in the comments to the answer itself for well... clarity:

短版本:本地变量可以只在一个寄存器中的(一个)cpu(s)(和cpu的核心中的一个,如果多个等)。这就像它得到的一样快。一个volatile变量必须检查其他内核/ caches / cpus /内存的变化,但细节可能是非常硬件特定的(缓存行,内存屏障等)。但是也有jvm具体,(热点服务器编译器可能例如提升非易失性变量),并且对可能的性能增益的重新排序指令施加限制

Short version: A local variable can just be in a register in (one of) the cpu(s) (and in one of the cpu's cores if multiple etc). That's as fast as it gets. A volatile variable must be checked for changes in other cores/caches/cpus/memory, but the details can be very hardware specific (cache lines, memory barriers etc). But also jvm specific, (the hotspot server compiler might hoist non volatile variables for example) and it imposes limits on reordering instructions for possible performance gains as well

这篇关于如何分配到局部变量帮助这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆