Java 7
我正在阅读 J. Bloch 的 effective Java,现在正在阅读有关延迟初始化字段的部分。他介绍了所谓的双重检查惯用法,如下:
public static void main(String[] args){
Test t = new Test();
long now = System.nanoTime();
t.getT();
long invokationTime = System.nanoTime() - now;
System.out.println(invokationTime); //Prints 3299 averagely
}
private static class Test{
private volatile Test field;
public Test getT(){
Test result = field; // <----- Note the local variable here
if(result != null){
synchronized (this) {
result = field;
if (result == null)
field = result = new Test();
}
}
return result;
}
}
他对使用局部变量给出了以下解释:
What this variable does is to ensure that field is read only once in the common case where it’s already initialized.
现在,让我们考虑以下代码:
public static void main(String[] args){
Test t = new Test();
long now = System.nanoTime();
t.getT();
long invokationTime = System.nanoTime() - now;
System.out.println(invokationTime); //Prints 3101 averagely
}
private static class Test{
private volatile Test field;
public Test getT(){
if(field != null){
synchronized (this) {
if (field == null)
field = new Test();
}
}
return field;
}
}
在我的机器上,第二种惰性初始化方法甚至更快。但在 ideone 的机器上,正如 J. Bloch 所说,他们使用了大约 7985 和 10630。那么是否值得使用这样的局部变量来进行优化呢?据我所知,读取和写入变量的成本几乎相等。
因此,只有当该方法主要由此类轻量级操作组成时,我们才应该担心它,对吗?
最佳答案
这是值得的,因为您已经确定急切加载和同步都太昂贵了。但实际上,几乎可以肯定不是。您实际需要双重检查锁定代码的情况往往是在非锁定数据结构和事物中。高性能代码的良好设计往往会将其插入孤立的位置,这样您就不会在每次接触代码时搬起石头砸自己的脚。
关于java - 类(class)阅读领域费用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33951862/