[英]In ArrayBlockingQueue, why copy final member field into local final variable?
In ArrayBlockingQueue
, all the methods that require the lock copy it to a local final
variable before calling lock()
.在
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();
}
}
Is there any reason to copy this.lock
to a local variable lock
when the field this.lock
is final
?当
this.lock
字段为final
时,是否有任何理由将this.lock
复制到局部变量lock
?
Additionally, it also uses a local copy of E[]
before acting on it:此外,它还在操作之前使用
E[]
的本地副本:
private E extract() {
final E[] items = this.items;
E x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}
Is there any reason for copying a final field to a local final variable?是否有任何理由将最终字段复制到本地最终变量?
It's an extreme optimization Doug Lea, the author of the class, likes to use.这是该类的作者 Doug Lea 喜欢使用的极端优化。 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.
这是关于 core-libs-dev 邮件列表的最近主题的一篇关于这个确切主题的帖子,它很好地回答了您的问题。
from the post:从帖子:
...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
...复制到本地会产生最小的字节码,对于低级代码,最好编写更接近机器的代码
This thread gives some answers. 这个线程给出了一些答案。 In substance:
实质上:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.