以下是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;