ArrayBlockingQueue:为什么不直接访问全局变量?

时间:2016-09-15 04:55:43

标签: java concurrency locking blockingqueue

在ArrayBlockingQueue实现中,为什么不直接访问全局变量?

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
            implements BlockingQueue<E>, java.io.Serializable {

    /** The queued items */
    final Object[] items;

    /** Main lock guarding all access */
    final ReentrantLock lock;

    // ...

    public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        // ...
    }

    @Override
    public E poll() {
        final ReentrantLock lock = this.lock; // Why the global variable assigned to a local variable ?
        lock.lock();
        try {
            return (count == 0) ? null : extract();
        } finally {
            lock.unlock();
        }
    }

}   

poll方法中,全局ReentrantLock lock变量被分配给局部变量并使用它的引用。为什么会这样?

1 个答案:

答案 0 :(得分:0)

局部变量存储在堆栈中并且访问速度更快。