简体   繁体   English

在 ArrayBlockingQueue 中,为什么要将 final 成员字段复制到本地 final 变量中?

[英]In ArrayBlockingQueue, why copy final member field into local final variable?

In ArrayBlockingQueue , all the methods that require the lock copy it to a local final variable before calling lock() .ArrayBlockingQueue中,所有需要锁的方法在调用lock()之前将其复制到本地final变量。

public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        if (count == items.length)
            return false;
        else {
            insert(e);
            return true;
        }
    } finally {
        lock.unlock();
    }
}

Is there any reason to copy this.lock to a local variable lock when the field this.lock is final ?this.lock字段为final时,是否有任何理由将this.lock复制到局部变量lock

Additionally, it also uses a local copy of E[] before acting on it:此外,它还在操作之前使用E[]的本地副本:

private E extract() {
    final E[] items = this.items;
    E x = items[takeIndex];
    items[takeIndex] = null;
    takeIndex = inc(takeIndex);
    --count;
    notFull.signal();
    return x;
}

Is there any reason for copying a final field to a local final variable?是否有任何理由将最终字段复制到本地最终变量?

It's an extreme optimization Doug Lea, the author of the class, likes to use.这是该类的作者 Doug Lea 喜欢使用的极端优化。 Here's a post on a recent thread on the core-libs-dev mailing list about this exact subject which answers your question pretty well.这是关于 core-libs-dev 邮件列表的最近主题的一篇关于这个确切主题的帖子,它很好地回答了您的问题。

from the post:从帖子:

...copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine ...复制到本地会产生最小的字节码,对于低级代码,最好编写更接近机器的代码

This thread gives some answers. 这个线程给出了一些答案。 In substance:实质上:

  • the compiler can't easily prove that a final field does not change within a method (due to reflection / serialization etc.)编译器不能轻易证明一个方法中的 final 字段没有改变(由于反射/序列化等)
  • most current compilers actually don't try and would therefore have to reload the final field everytime it is used which could lead to a cache miss or a page fault大多数当前的编译器实际上不会尝试,因此每次使用时都必须重新加载最终字段,这可能导致缓存未命中或页面错误
  • storing it in a local variable forces the JVM to perform only one load将其存储在局部变量中强制 JVM 仅执行一次加载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM