在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();
}
}
Run Code Online (Sandbox Code Playgroud)
当字段是什么时,有没有理由复制this.lock到局部变量?lockthis.lockfinal
此外,它还在使用E[]之前使用本地副本:
private E extract() {
final E[] items = this.items;
E x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}
Run Code Online (Sandbox Code Playgroud)
有没有理由将最终字段复制到本地最终变量?