jdk并发包 CopyOnWriteArrayList源代码分析

时间:2021-06-14 07:45:28

CopyOnWriteArrayList是jdk1.5并法包里面用于处理高并发下。读多写少的情况下。减少锁等待的集合类。以下对该类实现做一个简要的分析

1,首先CopyOnWriteArrayList是实现了List接口,对=List接口的相关方法进行了实现。

2,以下的它的add方法,会首先加锁,然后copy原List内部的数组,然后对新数组长度加1后释放锁。因为数组copy速度非常快,切在读多写少的情况下锁开销比較少

    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();
}
}

2,它的迭代器COWIterator不是高速失败的。以下是它的源代码

private COWIterator(Object[] elements, int initialCursor) {
cursor = initialCursor;
snapshot = elements;
} public boolean hasNext() {
return cursor < snapshot.length;
} public boolean hasPrevious() {
return cursor > 0;
} @SuppressWarnings("unchecked")
public E next() {
if (! hasNext())
throw new NoSuchElementException();
return (E) snapshot[cursor++];
}

3,以下是它的remove方法,加锁原理同add方法

    public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
E oldValue = get(elements, index);
int numMoved = len - index - 1;
if (numMoved == 0)
setArray(Arrays.copyOf(elements, len - 1));
else {
Object[] newElements = new Object[len - 1];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index + 1, newElements, index,
numMoved);
setArray(newElements);
}
return oldValue;
} finally {
lock.unlock();
}
}