在ArrayBlockingQueue中,为什么要将最终成员字段复制到本地最终变量中? [英] In ArrayBlockingQueue, why copy final member field into local final variable?

查看:105
本文介绍了在ArrayBlockingQueue中,为什么要将最终成员字段复制到本地最终变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ArrayBlockingQueue 中,所有需要锁定的方法在调用<$之前将其复制到本地 final 变量c $ c> lock()。

In ArrayBlockingQueue, all the methods that require the lock copy it to a local final variable before calling lock().

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();
    }
}

有没有理由复制 this.lock 到一个局部变量 lock 当字段 this.lock final

Is there any reason to copy this.lock to a local variable lock when the field this.lock is final?

此外,它还使用 E [] 在采取行动之前:

Additionally, it also uses a local copy of E[] before acting on it:

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

是否有任何理由将最终字段复制到本地最终字段变量?

推荐答案

这是一个极端优化,该课程的作者Doug Lea喜欢使用。这是关于最近的一个主题的帖子在core-libs-dev邮件列表中关于这个确切的主题,很好地回答了你的问题。

It's an extreme optimization Doug Lea, the author of the class, likes to use. 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.

来自帖子:


...复制到本地生成最小的
字节码,对于低级代码,编写更接近机器的代码
很好

...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

这篇关于在ArrayBlockingQueue中,为什么要将最终成员字段复制到本地最终变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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