如何解决ArrayList线程不安全
- 方法1:使用Vector
- 方法2:使用Collections工具类中的Collections.synchronizedList(new ArrayList) 方法
- 方法3:JUC下的CopyOnWriteArrayList类,写时复制
1. 类图
写时复制、读写分离
public class CopyOnWriteArrayList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}
2. 成员变量
/** The lock protecting all mutators */
// 可重入锁,执行数组的变换操作时加锁,get操作不用加锁(读共享、写独享)
final transient ReentrantLock lock = new ReentrantLock();
/** The array, accessed only via getArray/setArray. */
// 可见性、有序性,存放元素的数组
private transient volatile Object[] array;
// get、set方法
final Object[] getArray() {
return array;
}
/**
* Sets the array.
*/
final void setArray(Object[] a) {
array = a;
}
3.构造方法
public CopyOnWriteArrayList() {
setArray(new Object[0]);
}
/**
* Creates a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection of initially held elements
* @throws NullPointerException if the specified collection is null
*/
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);
}
/**
* Creates a list holding a copy of the given array.
*
* @param toCopyIn the array (a copy of this array is used as the
* internal array)
* @throws NullPointerException if the specified array is null
*/
public CopyOnWriteArrayList(E[] toCopyIn) {
setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
}
4.方法
4.1 add方法
- _public boolean _add(E e):末尾添加元素
- _public void _add(_int _index, E element) :指定位置添加元素
- _public boolean _addIfAbsent(E e):如果不存在加入元素
- _public boolean _addAll(Collection<? _extends _E> c)
- _public boolean _addAll(_int _index, Collection<? _extends _E> c)
_public boolean _add(E e)
public boolean add(E e) {
final ReentrantLock lock = this.lock;
// 获取独占锁
lock.lock();
try {
// 获取数组内容
Object[] elements = getArray();
// 长度
int len = elements.length;
// 复制一份新的,长度为原长度+1
Object[] newElements = Arrays.copyOf(elements, len + 1);
// 放入结尾新增的元素e
newElements[len] = e;
// 重新赋值原数组
setArray(newElements);
return true;
} finally {
// 释放独占锁
lock.unlock();
}
}
- CopyOnWriteArrayList是如何保证【写】时线程安全的?因为用了ReentrantLock独占锁,保证同时只有一个线程对集合进行修改操作。
- 数据是存储在CopyOnWriteArrayList中的array数组中的。
- 在添加元素的时候,并不是直接往array里面add元素,而是复制出来了一个新的数组,并且复制出来的数组的长度是 【旧数组的长度+1】,再把旧的数组替换成新的数组,这是尤其需要注意的。
_public void _add(_int _index, E element)
public void add(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
// index合法性检查
if (index > len || index < 0)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+len);
// 以下添加元素的思想同ArrayList
Object[] newElements;
// 获取移动的元素个数
int numMoved = len - index;
if (numMoved == 0)
// 复制新的,在末尾添加就可以了
newElements = Arrays.copyOf(elements, len + 1);
else {
// 在index前后分段复制
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();
}
}
_public boolean _addIfAbsent(E e)
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
// 先判断当前快照的数组有没有这个元素,没有就进入addIfAbsent方法添加
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);
}
/**
* A version of addIfAbsent using the strong hint that given
* recent snapshot does not contain e.
*/
// 快照加
private boolean addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
// 如果快照和当前最新的数组地址不一致,说明被别的线程动了
if (snapshot != current) {
// Optimize for lost race to another addXXX operation
// 计算较小的长度
int common = Math.min(snapshot.length, len);
// 遍历,
for (int i = 0; i < common; i++)
// 如果当前数组和快照数组中i对应的位置的值不相等,且
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
if (indexOf(e, current, common, len) >= 0)
return false;
}
// 否则,没有别人动,可以添加
Object[] newElements = Arrays.copyOf(current, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
存快照
4.2 查找方法
- _public boolean _contains(Object o)
- _public _E get(_int _index) :共享的不加锁。存在弱一致性问题,别人修改的时候该线程不知道
public E get(int index) {
return get(getArray(), index);
}
private E get(Object[] a, int index) {
return (E) a[index];
}
// 取当前的array查询
public boolean contains(Object o) {
Object[] elements = getArray();
return indexOf(o, elements, 0, elements.length) >= 0;
}
private static int indexOf(Object o, Object[] elements,
int index, int fence) {
if (o == null) {
for (int i = index; i < fence; i++)
if (elements[i] == null)
return i;
} else {
for (int i = index; i < fence; i++)
if (o.equals(elements[i]))
return i;
}
return -1;
}
4.3 修改方法
public E set(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 拿到当前的array数组
Object[] elements = getArray();
E oldValue = get(elements, index);
如果oldValue和新值不相等
if (oldValue != element) {
int len = elements.length;
// 先复制一份,在新数组中修改,在重新赋值回去
Object[] newElements = Arrays.copyOf(elements, len);
newElements[index] = element;
setArray(newElements);
} else {
// 为了保证volatile 语义,即使没有修改,也要替换成新的数组
// Not quite a no-op; ensures volatile write semantics
setArray(elements);
}
return oldValue;
} finally {
lock.unlock();
}
}
4.4 删除方法
根据值删除
// 如果存在,删除第一个出现的o元素;否则不变
public boolean remove(Object o) {
Object[] snapshot = getArray();
int index = indexOf(o, snapshot, 0, snapshot.length);
return (index < 0) ? false : remove(o, snapshot, index);
}
// 找它所在的位置,返回坐标
private static int indexOf(Object o, Object[] elements,
int index, int fence) {
if (o == null) {
for (int i = index; i < fence; i++)
if (elements[i] == null)
return i;
} else {
for (int i = index; i < fence; i++)
if (o.equals(elements[i]))
return i;
}
return -1;
}
// 快照删
private boolean remove(Object o, Object[] snapshot, int index) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
if (snapshot != current) findIndex: {
int prefix = Math.min(index, len);
for (int i = 0; i < prefix; i++) {
if (current[i] != snapshot[i] && eq(o, current[i])) {
index = i;
break findIndex;
}
}
if (index >= len)
return false;
if (current[index] == o)
break findIndex;
index = indexOf(o, current, index, len);
if (index < 0)
return false;
}
Object[] newElements = new Object[len - 1];
System.arraycopy(current, 0, newElements, 0, index);
System.arraycopy(current, index + 1,
newElements, index,
len - index - 1);
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
根据下标删除
public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
// 获取该位置的元素oldValue
E oldValue = get(elements, index);
// 计算移动的个数
int numMoved = len - index - 1;
// 如果移动个数为0
if (numMoved == 0)
// 为了保证volatile 语义,即使没有修改,也要替换成新的数组
setArray(Arrays.copyOf(elements, len - 1));
else {
// 否则,需要删除,同样new一个新数组进行操作,最后再重新赋值
Object[] newElements = new Object[len - 1];
// 在index前后分两段复制
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index + 1, newElements, index,
numMoved);
setArray(newElements);
}
return oldValue;
} finally {
lock.unlock();
}
}