先附上BlockingQueue源码take()代码:public class ArrayBlockingQueue implements BlockingQueue { final ReentrantLock lock; //构造体中初始化lock
public ArrayBlockingQueue(){ //...
} 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())??为什么要多此一举呢?
本文详细分析了ArrayBlockingQueue在Java并发编程中的实现,重点关注其take()方法。通过阅读源码,我们可以看到在take()方法中,全局final ReentrantLock lock被赋值给一个局部变量。这种做法是为了避免在同步块外直接引用this.lock,减少锁对象的可见性问题,提高并发安全性。同时,局部变量可以减少内存引用,优化性能。
650

被折叠的 条评论
为什么被折叠?



