我是靠谱客的博主 英勇草莓,最近开发中收集的这篇文章主要介绍CopyOnWriteArrayList(写时copy的ArrayList),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

CopyOnWriteArrayList(写时copy的ArrayList)

因为ArrayList采用的是fail-fast机制,在迭代遍历的过程中,如果list的结构发生了变化[structurally modified],一般形如add,remove,clear操作,就会抛出ConcurrentModificationException,是线程不安全的,相反的,CopyOnWriteArrayListjava.util.concurrent包下,这个是为并发而设计的

元素结构修改

CopyOnWriteArrayList中add方法:

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

步骤:

  • 加锁
  • 获取原数据的一个副本
  • copy副本到一个新的Object[]数组newElements中
  • 将新增元素放在newElements的最后
  • array的引用重新指向newElements
  • 释放锁

遍历

COWIteratorCopyOnWriteArrayList中的静态内部类,用于遍历迭代数据

static final class COWIterator<E> implements ListIterator<E> {
/** Snapshot of the array */
private final Object[] snapshot;
/** Index of element to be returned by subsequent call to next.
*/
private int cursor;
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++];
}
@SuppressWarnings("unchecked")
public E previous() {
if (! hasPrevious())
throw new NoSuchElementException();
return (E) snapshot[--cursor];
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor-1;
}
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code remove}
*
is not supported by this iterator.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code set}
*
is not supported by this iterator.
*/
public void set(E e) {
throw new UnsupportedOperationException();
}
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code add}
*
is not supported by this iterator.
*/
public void add(E e) {
throw new UnsupportedOperationException();
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
Object[] elements = snapshot;
final int size = elements.length;
for (int i = cursor; i < size; i++) {
@SuppressWarnings("unchecked") E e = (E) elements[i];
action.accept(e);
}
cursor = size;
}
}

可以看到CopyOnWriteArrayList在迭代过程中不支持add,set,remove等操作,并且迭代的数据是elements的一个snapshot快照,对原list.iterator操作之后新增的数据不再遍历,不难解释下面问题了

@Test
public void copyOnWriteArrayListTest(){
List<String> temp = new ArrayList<>();
temp.add("aaa");
temp.add("bbb");
temp.add("ccc");
List<String> list = new CopyOnWriteArrayList<>(temp);
Iterator<String> iterator = list.iterator();
list.add("ddd"); //不会输出
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
// 输出
// aaa
// bbb
// ccc

因为在修改的CopyOnWriteArrayList时会复制之前的数据,所以CopyOnWriteArrayList适合读多写少的情况

最后

以上就是英勇草莓为你收集整理的CopyOnWriteArrayList(写时copy的ArrayList)的全部内容,希望文章能够帮你解决CopyOnWriteArrayList(写时copy的ArrayList)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部