为什么在调用其方法(最佳实践或出于特定原因)之前将最终字段变量分配给本地副本? [英] Why assign a final field variable to a local copy before calling its method (Best Practice or for a specific reason)?
本文介绍了为什么在调用其方法(最佳实践或出于特定原因)之前将最终字段变量分配给本地副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
检查 ArrayBlockingQueue
的源代码时,我注意到在调用对象实例的任何方法之前,已将最终字段分配给局部变量。这是为了达到特定目的吗?
When checking the source code of ArrayBlockingQueue
I noticed that before calling on any method of an object instance, a final field has been assigned to a local variable. Is this done to achieve a specific purpose?
public E peek() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : items[takeIndex];
} finally {
lock.unlock();
}
}
推荐答案
那里是关于此处的讨论。基本上它是一种优化,允许更快地访问锁。即使this.lock是最终的,jvm仍然会在每次访问this.lock时进行字段查找,通过制作最终副本,它会稍快一点。
There is a discussion about that here. Basically it is an optimization, allowing quicker access to the lock. Even though this.lock is final, the jvm still does a field lookup every time this.lock is accessed, by making a final copy, it is slightly faster.
这篇关于为什么在调用其方法(最佳实践或出于特定原因)之前将最终字段变量分配给本地副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文