在 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;
}
是否有任何理由将 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/