在ArrayBlockingQueue 中,为什么要将final 成员字段复制到本地final 变量中? [英] In ArrayBlockingQueue, why copy final member field into local final variable?
问题描述
在ArrayBlockingQueue
中,所有需要锁的方法在调用lock()
之前将其复制到本地final
变量中.
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
字段为 final<时,是否有任何理由将
this.lock
复制到局部变量 lock
/代码>?
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;
}
是否有任何理由将 final 字段复制到局部 final 变量?
Is there any reason for copying a final field to a local final variable?
推荐答案
这是该类的作者 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 中,为什么要将final 成员字段复制到本地final 变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!