为什么CopyOnWriteArrayList使用引用实例变量的局部变量?

时间:2014-10-01 06:19:25

标签: java

以下是jdk concurrent对CopyOnWriteArrayList

的定义
private volatile transient Object[] array;
transient final ReentrantLock lock = new ReentrantLock();


public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }

为什么add函数定义了另一个锁(final ReentrantLock lock = this.lock;),它也将实例变量(lock)引用为本地可行,而不是直接使用实例变量?

add功能可以实现为:

int len = array.length;
Object[] newElements = Arrays.copyOf(array, len + 1);
newElements[len] = o;
array = newElements;

0 个答案:

没有答案