在 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.lock
为 final< 时,是否有任何理由将
?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;
}
是否有任何理由将最终字段复制到本地最终变量?
最佳答案
这是该类的作者 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/62281877/