为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

POPMUISE 2018-11-13 14:32:13
先附上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())??为什么要多此一举呢?
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

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



变量使用n次就可以省下n-1次的开销


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

太底层了,忽略吧


查看完整回答
反对 回复 2018-11-13
  • 1 回答
  • 0 关注
  • 496 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信