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
的时候,将其复制到本地变量 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;
}
将final字段复制到本地final变量中,是否有任何理由?