CopyOnWriteArrayList简单阅读源码
CopyOnWriteArrayList是Java并发包中提供的一个并发容器,它是个线程安全且读操做无锁的ArrayList,写操做则经过建立底层数组的新副原本实现,是一种读写分离的并发策略,咱们也能够称这种容器为"写时复制器",Java并发包中相似的容器还有CopyOnWriteSet。本文会对CopyOnWriteArrayList的实现原理及源码进行分析。数组
集合框架中的ArrayList是非线程安全的,Vector虽是线程安全的,但因为简单粗暴的锁同步机制,性能较差。而CopyOnWriteArrayList则提供了另外一种不一样的并发处理策略(固然是针对特定的并发场景)。安全
不少时候,咱们的系统应对的都是读多写少的并发场景。CopyOnWriteArrayList容器容许并发读,读操做是无锁的,性能较高。至于写操做,好比向容器中添加一个元素,则首先将当前容器复制一份,而后在新副本上执行写操做,结束以后再将原容器的引用指向新容器。并发
了解了CopyOnWriteArrayList的实现原理,分析它的优缺点及使用场景就很容易了。app
优势:框架
读操做性能很高,由于无需任何同步措施,比较适用于读多写少的并发场景。Java的list在遍历时,若中途有别的线程对list容器进行修改,则会抛出ConcurrentModificationException异常。而CopyOnWriteArrayList因为其"读写分离"的思想,遍历和修改操做分别做用在不一样的list容器,因此在使用迭代器进行遍历时候,也就不会抛出ConcurrentModificationException异常了ide
缺点:源码分析
缺点也很明显,一是内存占用问题,毕竟每次执行写操做都要将原容器拷贝一份,数据量大时,对内存压力较大,可能会引发频繁GC;二是没法保证明时性,Vector对于读写操做均加锁同步,能够保证读和写的强一致性。而CopyOnWriteArrayList因为其实现策略的缘由,写和读分别做用在新老不一样容器上,在写操做执行过程当中,读不会阻塞但读取到的倒是老容器的数据。性能
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#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(); } } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). Returns the element that was removed from the list. * * @throws IndexOutOfBoundsException {@inheritDoc} */ 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(); } }
最重要的区别就是synchronizedthis
/** * Removes the first (lowest-indexed) occurrence of the argument * from this vector. If the object is found in this vector, each * component in the vector with an index greater or equal to the * object's index is shifted downward to have an index one smaller * than the value it had previously. * * <p>This method is identical in functionality to the * {@link #remove(Object)} method (which is part of the * {@link List} interface). * * @param obj the component to be removed * @return {@code true} if the argument was a component of this * vector; {@code false} otherwise. */ public synchronized boolean removeElement(Object obj) { modCount++; int i = indexOf(obj); if (i >= 0) { removeElementAt(i); return true; } return false; }