在阅读ArrayBlockingQueue的源代码时,我在下面找到了代码:
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == 0)
notEmpty.await();
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
throw ie;
}
E x = extract();
return x;
} finally {
lock.unlock();
}
}
为什么不使用代码
public E take() throws InterruptedException {
lock.lockInterruptibly();
try {
try {
while (count == 0)
notEmpty.await();
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
throw ie;
}
E x = extract();
return x;
} finally {
lock.unlock();
}
}
行代码的好处是什么:最终的ReentrantLock lock = this.lock;
答案 0 :(得分:0)
这个想法由Doug Lea推广 - 我认为最初的想法是当使用最终的局部变量时,JVM可能会执行一些与性能相关的优化。
从OpenJDK线程中查看this线程,讨论这个问题
编辑:
一些研究在堆栈上提出了这两个相关的问题:
In ArrayBlockingQueue, why copy final member field into local final variable?