目录
ArrayList的存储结构是数组,在添加或删除元素后都将之后的元素一个个移位,且对于数组目标位置的操作都是++或--,明显是线程不安全的。
如果添加元素之前发现容量不足则扩容,默认扩大为1.5倍。
值得一提的是,如果一个线程对集合进行修改,同时另一个线程在遍历此数组,有可能会抛出Fail-Fast异常
(因为iterator创建时的modCount和next或remove时的modCount不相等,表示遍历期间数组发生了增加删除等操作)。
CopyOnWriteArrayList的存储结构为volatile修饰的数组+lock锁。
对元素进行操作时先对整个数组加锁,然后创建一个新数组,将原数组copy进去并进行修改,这样原数组的读不受影响。对于上述遍历的情况,是Fail-Safe机制,因为遍历的是原数组的快照。
其原理就是写时复制,每次add、set、remove操作都需要重新copy数组,所以适用于读多写少的情景。
而且不保证实时一致性,只能保证最终一致性。
ArrayList【线程不安全】
1. ArrayList存储结构、构造函数
存储结构
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
}
构造函数
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
如果不指定大小,那么会初始化一个空的数组;
2.【ArrayList功能实现】——add
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
- 首先判断是否需要扩容
- 如果是直接添加元素,那么elementData[size++] = e;在数组的最后一个位置放置此值
- 如果指定了元素的位置,System.arraycopy(elementData, index, elementData, index + 1,
size - index)
那么将index之后的数据都向后移位。
注意这里的size++,是一个典型的非线程安全的操作。
3.【ArrayList功能实现】——remove
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
都是找到目标index,然后
System.arraycopy(elementData, index+1, elementData, index,numMoved);
将删除元素之后的数据都前移,然后将目标index位置置为null.
不同的是:
- 通过index删除元素,返回的是原Value;
- 通过Object删除元素,返回的是boolean是否成功;
4.【ArrayList功能实现】——扩容
//minCapacity:目前需要的容量
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
如果当前的elementData数组是DEFAULTCAPACITY_EMPTY_ELEMENTDATA(表示初始化时未声明数组大小),且minCapacity<10,那么返回10;
否则直接返回minCapacity。
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
扩容的数组大小:oldCapacity + (oldCapacity >> 1),即原数组大小的1.5倍
5.【fail-fast】错误机制
- 产生时机:当有一个线程对某个集合进行修改操作,而另一个线程在遍历此集合时,会有可能产生fail-fast错误。
但是迭代器的fail-fast并不一定会发生,当存在并发的修改操作时,不能保证错误一定被抛出。 - 产生原因:在ArrayList的遍历器中,next、remove等操作中都有checkForComodification的检查
private class Itr implements Iterator<E> {
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
- modCount是ArrayList的属性,表示集合被修改的次数,在增加删除等操作中都会将此值+1;
- expectedModCount的值在迭代器创建时被赋值为modCount;
这样在迭代器遍历过程中,如果有其他线程修改了ArrayList,那么这两个值不相等,抛出异常。
解决方法:使用Fail-Safe机制的CopyOnWriteArrayList.
CopyOnWriteArrayList【线程安全】
1. CopyOnWriteArrayList存储结构、构造函数
存储结构
public class CopyOnWriteArrayList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
/** The lock protecting all mutators */
final transient ReentrantLock lock = new ReentrantLock();
/** The array, accessed only via getArray/setArray. */
private transient volatile Object[] array;
}
构造函数
final void setArray(Object[] a) {
array = a;
}
public CopyOnWriteArrayList() {
setArray(new Object[0]);
}
public CopyOnWriteArrayList(Collection<? extends E> c) {
Object[] elements;
if (c.getClass() == CopyOnWriteArrayList.class)
elements = ((CopyOnWriteArrayList<?>)c).getArray();
else {
elements = c.toArray();
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elements.getClass() != Object[].class)
elements = Arrays.copyOf(elements, elements.length, Object[].class);
}
setArray(elements);
}
2.【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();
}
}
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;
setArray(newElements);
} finally {
lock.unlock();
}
}
- 在新增元素之前,首先先获取lock可重入锁,加锁;
- 创建一个size+1大小的新数组
- 将原数组copy到新数组,并将length位置赋值;
- 将新数组setArray替换原数组
- 解锁
这里对于数组的修改是在新的数组上进行的,对于原数组的读操作不产生影响;
3.【CopyOnWriteArrayList功能实现】——COWIterator迭代器
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 E next() {
if (! hasNext())
throw new NoSuchElementException();
return (E) snapshot[cursor++];
}
可见CopyOnWriteArrayList中迭代器是存储了一个 ArrayList的快照 ,当另外的线程对数组进行修改时,snapshot中的数据并不受影响。
总结——写时复制
- CopyOnWriteArrayList是 “写时复制” ,每次add、set、remove等操作都需要重新 copy数组 ,代价很高,易造成内存消耗;适用于 读多写少 的场景。
- 不能保证数据的实时一致性,只能保证最终一致性。