在ArrayBlockingQueue
中,所有需要锁定的方法在调用final
之前将其复制到本地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
为lock
时,是否有任何理由将this.lock
复制到局部变量final
?此外,在对其执行操作之前,它还使用
E[]
的本地副本:private E extract() {
final E[] items = this.items;
E x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}
有什么理由将最终字段复制到本地最终变量?
最佳答案
该类的作者Doug Lea喜欢使用这种极端的优化方法。这是core-libs-dev邮件列表上a recent thread上的一则帖子,内容与此确切,可以很好地回答您的问题。
从帖子:
...复制到当地人产生最小的
字节码,对于低级代码,编写代码很好
离机器更近了