为什么在Joshua Bloch Effective Java示例中,双重检查锁定的速度提高了25% [英] Why Double checked locking is 25% faster in Joshua Bloch Effective Java Example

查看:117
本文介绍了为什么在Joshua Bloch Effective Java示例中,双重检查锁定的速度提高了25%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是Effective Java 2nd Edition的片段。在这里,作者声称下面的代码比你不使用结果变量快25%。
根据书这个变量的作用是确保字段在已经初始化的常见情况下只读一次。 。
我无法理解为什么这个代码在初始化之后快速比较,如果我们不使用Local变量结果。在任何一种情况下,无论你是否使用局部变量结果,你在初始化后只有一个易失性读数。

Hi below is the snippet from Effective Java 2nd Edition. Here the author claims the following piece of code is 25% faster more than in which u do not use result variable. According to the book "What this variable does is to ensure that field is read only once in the common case where it’s already initialized." . I am not able to understand why this code would be fast after the value is initialized as compare to of if we do not use the Local variable result. In either case you will have only one volatile read after initialization whether you use the local variable result or not.

// Double-check idiom for lazy initialization of instance fields 
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;
}


推荐答案

一旦 field 已初始化,代码为:

Once field has been initialised, the code is either:

if (field == null) {...}
return field;

或:

result = field;
if (result == null) {...}
return result;

在第一种情况下,您读取两次volatile变量,而在第二种情况下,您只读取一次。虽然易失性读取非常快,但它们比从局部变量读取要慢一些(我不知道它是否为25%)。

In the first case you read the volatile variable twice whereas in the second you only read it once. Although volatile reads are very fast, they can be a little slower than reading from a local variable (I don't know if it is 25%).

注意:


  • 易失性读取与最近处理器(至少x86)/ JVM上的正常读取一样便宜,即没有区别。

  • 然而,编译器可以更好地优化代码而不会出现波动,因此您可以从更好的编译代码中获得效率。

  • 无论如何,几纳秒的25%仍然不多。

  • 这是一个标准的习惯用法,可以在java.util.concurrent包的许多类中找​​到 - 例如参见这个方法在ThreadPoolExecutor中(有很多他们)

  • volatile reads are as cheap as normal reads on recent processors (at least x86)/JVMs, i.e. there is no difference.
  • however the compiler can better optimise a code without volatile so you could get efficiency from better compiled code.
  • 25% of a few nanoseconds is still not much anyway.
  • it is a standard idiom that you can find in many classes of the java.util.concurrent package - see for example this method in ThreadPoolExecutor (there are many of them)

这篇关于为什么在Joshua Bloch Effective Java示例中,双重检查锁定的速度提高了25%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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