在ArrayBlockingQueue中,为什么将final成员字段复制到局部final变量中?
在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;
}
是否有任何理由将最终字段复制到本地最终变量?
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();
}
}
Is there any reason to copy this.lock
to a local variable lock
when the field this.lock
is final
?
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;
}
Is there any reason for copying a final field to a local final variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是该课程的作者 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.
from the post:
此帖子给出了一些答案。实质上:
This thread gives some answers. In substance: