关于Java BlockingQueue源码学习的一个问题

先附上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())??为什么要多此一举呢?

阅读 2.3k
2 个回答

复制进来可以减少接下来“获取字段”的开销
算是挤性能吧

stackoverflow上有相同问题

...copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine

太底层了,忽略吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题