用途与特色
可用于多读取,写入须要线程安全的状况使用。算法
实现算法数组
该集合如其名字同样,是先建立一个新的数组,而后将旧的数组copy到新数组中,再切换数组引用。而且该数组是在每次添加时都会执行以上流程,因此不建议在多写入的场景使用。安全
该集合在多并发时使用ReentrantLock锁来处理并发问题,比Vector中synchronized的效率会高一些,但在并法过程当中可能会出现脏读问题,如两个线程一个执行读取数组数量,一个在作写入操做,如在写入操做以前,还没作size++操做前,另一个线程读取size值,此时还时未增长的数量,会产生脏读。并发
添加app
/** * 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(); } }
删除this
这里说明一下,以前的几个集合在删除操做时都是不会对object[]数组进行操做,但这个集合会从新生成-1的新数组。因此能够说该集合的数组长度与集合的实际数据占用长度是相同的。线程
/** * 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(); } }
扩容机制code
扩容时机:在增长数据时,没增长一个扩容一个blog
是否线程安全,为何?ci
线程安全,在源码中对数据操做使用ReentrantLock方法,保证了并发锁。
具体ReentrantLock的使用详解与synchronized有何区别,会在以后详细查看并发时作补充。
根据jdk1.8版本源码解读