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

标签 java multithreading optimization final local-variables

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

当字段 this.lockfinal< 时,是否有任何理由将 this.lock 复制到局部变量 lock/?

此外,在对其执行操作之前,它还使用了 E[] 的本地副本:

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

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

最佳答案

这是该类(class)的作者 Doug Lea 喜欢使用的极端优化。这是关于 a recent thread 的帖子在关于这个确切主题的 core-libs-dev 邮件列表上,它很好地回答了你的问题。

来自帖子:

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

关于java - 在ArrayBlockingQueue中,为什么将final成员字段复制到本地final变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30167968/

相关文章:

Java hibernate 分离条件、计数/拥有、查询

java - SWT 按钮图像限制

c++ - 在哪里可以下载 pthread.h、semaphore.h 及其库?

c# - 从 TypeBuilder.CreateType 返回的类型的 Activator.CreateInstance 抛出 ArgumentException

c# - .NET (C#) 中 64 位应用程序的性能优势

python - 如何优化这个数据平滑Python循环?

c++ - 打印一系列数字优化第 1 部分

java - 使用不确定元素对 json 数据建模

c# - 设置 Backgroundworker MVVM,更新 Progressbar

java - 从Gradle中删除Play服务 map 实现