先附上BlockingQueue源码take()代码:
public class ArrayBlockingQueue<E> implements BlockingQueue<E> {
final ReentrantLock lock;
//构造体中初始化lock
public ArrayBlockingQueue<E>(){
//...
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock; //疑惑
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
}
请问take方法中,第一行final ReentrantLock lock = this.lock,为什么要把全局字段lock先复制到一个局部变量中使用呢???直接使用全局final lock不可以吗(eg. this.lock.lockInterruptibly())??为什么要多此一举呢?
复制进来可以减少接下来“获取字段”的开销
算是挤性能吧