【问题标题】:ArrayBlockingQueue: Why global variables are not accessed directly?ArrayBlockingQueue:为什么不直接访问全局变量?
【发布时间】:2016-09-15 04:55:43
【问题描述】:

在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 变量被分配给一个局部变量并使用它的引用。为什么会这样?

【问题讨论】:

    标签: java concurrency locking blockingqueue


    【解决方案1】:

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

    【讨论】:

    • 这不是网站正在寻找的答案,这充其量只是一个评论,而且是一个糟糕的评论。
    猜你喜欢
    • 2012-02-26
    • 2022-01-15
    • 2019-05-04
    • 2021-12-10
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    相关资源
    最近更新 更多