gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:48:34 26 4
gpt4 key购买 nike

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 变量中?

最佳答案

这是类的作者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/2785964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com