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 implements ListIterator {
     /** 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(Consumersuper 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 temp = new ArrayList<>();
    temp.add("aaa");
    temp.add("bbb");
    temp.add("ccc");
    List list = new CopyOnWriteArrayList<>(temp);
    Iterator iterator = list.iterator();
    list.add("ddd"); //不会输出
    while (iterator.hasNext()){
        System.out.println(iterator.next());
    }
}
// 输出
// aaa
// bbb
// ccc

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

你可能感兴趣的:(concurrent)