列表容器常见的有
ArrayList
和LinkedList
,然而二者都是非线程安全的,若应用场景对线程安全有需求,则可使用CopyOnWriteArrayList
来代替传统的Vector
java
先看下类中定义的成员变量, 一个数组和一个锁数组
/** The lock protecting all mutators */ final transient ReentrantLock lock = new ReentrantLock(); /** The array, accessed only via getArray/setArray. */ private transient volatile Object[] array;
array: 保存了列表中的数据安全
lock: 修改时加锁,用于保证线程安全数据结构
底层数据结构依然是数组,相交于ArrayList
而言,少了一个表示数组长度的size
变量,获取列表长度是经过下面的方法多线程
public int size() { return getArray().length; } final Object[] getArray() { return array; }
留一个问题:并发
为何获取链表的长度个ArrayList的使用姿式不一样,这样作有什么好处源码分析
读数据,带两个疑问进行看源码性能
先看实现源码学习
private E get(Object[] a, int index) { return (E) a[index]; } /** * {@inheritDoc} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { return get(getArray(), index); }
结果比较清晰测试
private transient volatile Object[] array;
直接在源码中加上一些注释
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) { // 删除最后一个元素时 //直接进行数组拷贝,而后将tables数组引用指向拷贝后的数组 setArray(Arrays.copyOf(elements, len - 1)); } else { // 建立一个新的数组,将旧数组内容拷贝到新数组中 // 而后将tables数组引用指向新的数组 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(); } }
从删除的实现,可肯定如下几点:
ArrayList
新增元素时,可能致使数组扩容;CopyOnWriteArrayList
在列表的修改时,采用数组拷贝,在新的数组上进行操做,从这点出发,应该不存在扩容的问题,由于每次修改都会致使数组的从新拷贝
从代码出发,验证上面的观点
public void add(int index, E element) { final ReentrantLock lock = this.lock; // 新增,先加锁 lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (index > len || index < 0) { // 数组越界判断 throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+len); } Object[] newElements; int numMoved = len - index; // 将原数组拷贝到新的数组中 if (numMoved == 0) { // 添加在最后一个 newElements = Arrays.copyOf(elements, len + 1); } else { // 添加到中间,须要两次拷贝 newElements = new Object[len + 1]; System.arraycopy(elements, 0, newElements, 0, index); System.arraycopy(elements, index, newElements, index + 1, numMoved); } // 直接将数据添加到新的数组 newElements[index] = element; // 将tables引用指向新的数组 setArray(newElements); } finally { lock.unlock(); } }
从实现得出如下几个结论
CopyOnWriteArrayList
没有数组扩容一说,由于每次修改都会建立一个新的数组新增元素示意图
在List的遍历过程当中,新增,删除or修改其中元素值时,会出现什么问题?
先写个测试demo
public class CopyOnWriteTest { List<String> list = new CopyOnWriteArrayList<>( new String[]{ "1", "2", "3", "4", "5", "6", "7", "8", "9" } ); private void modify() { new Thread(() -> { list.add(8, "a8"); list.remove(9); list.set(6, "6666"); System.out.println("----修改完成----"); }).start(); } @Test public void testModify() throws InterruptedException { Iterator<String> iterable = list.iterator(); int i = 0; while (iterable.hasNext()) { if (i++ == 1) { modify(); } else if (i == 4) { Thread.sleep(1000); } System.out.println("index: " + i + " value: " + iterable.next()); } Thread.sleep(1000); System.out.println(list); } }
输出结果
index: 1 value: 1 index: 2 value: 2 index: 3 value: 3 ----修改完成---- index: 4 value: 4 index: 5 value: 5 index: 6 value: 6 index: 7 value: 7 index: 8 value: 8 index: 9 value: 9 [1, 2, 3, 4, 5, 6, 6666, 8, a8]
发如今迭代的过程当中,对列表进行修改,是不会影响迭代过程的,遍历的依然是原来的数组;(顺带说一句,若是换成ArrayList会抛并发修改的异常)
探究下原理,主要是由于 CopyOnWriteArrayList
的迭代器的实现方式
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(); } }
从源码分析可得知
List容器中,
Vector
和CopyOnWriteArrayList
都是线程安全的,下面则主要对比下二者的实现逻辑
Vector
CopyOnWriteArrayList
array
)ArrayList
低;读取无锁,因此读的性能比Vector
高(没有竞争)