文章目录
CopyOnWriteArrayList是ArrayList的线程安全版本,内部也是通过数组实现,每次对数组的修改都完全拷贝一份新的数组来修改,修改完了再替换掉老数组,这样保证了只阻塞写操作,不阻塞读操作,实现读写分离。
继承体系
- CopyOnWriteArrayList实现了List, RandomAccess, Cloneable, java.io.Serializable等接口。
- CopyOnWriteArrayList实现了List,提供了基础的添加、删除、遍历等操作。
- CopyOnWriteArrayList实现了RandomAccess,提供了随机访问的能力。
- CopyOnWriteArrayList实现了Cloneable,可以被克隆。
- CopyOnWriteArrayList实现了Serializable,可以被序列化。
源码解析
1.属性
//对数组修改时进行加锁
final transient ReentrantLock lock = new ReentrantLock();
//存储元素的数组
private transient volatile Object[] array;
2.构造方法
无参构造
public CopyOnWriteArrayList() {
//通过set方法直接创建一个空数组
setArray(new Object[0]);
}
参数为Collection的构造方法
public CopyOnWriteArrayList(Collection<? extends E> c) {
Object[] elements;
if (c.getClass() == CopyOnWriteArrayList.class)
//如果传入的集合是一个CopyOnWriteArrayList类型,直接把c的数组拿来使用
elements = ((CopyOnWriteArrayList<?>)c).getArray();
else {
//c不是CopyOnWriteArrayList类型,toArray把集合转为数组
elements = c.toArray();
// c.toArray might (incorrectly) not return Object[] (see 6260652)
//把数组的返回值类型转换为Object[]
if (elements.getClass() != Object[].class)
elements = Arrays.copyOf(elements, elements.length, Object[].class);
}
//把创建的elements数组赋值给array
setArray(elements);
}
参数为E的构造方法
public CopyOnWriteArrayList(E[] toCopyIn) {
//直接把数组拷贝给array
setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
}
2.添加元素
add(E e)
public boolean add(E e) {
final ReentrantLock lock = this.lock;
//加锁确保线程安全
//使用try--finally确保锁在使用结束释放
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();
}
}
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;
//越界检测
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();
}
}
addIfAbsent(E e)
如果e不在集合中才进行添加操作,类似于set去重
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
//判断如果e在数组中不添加,否则添加元素
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);
}
//如果o在elements数组中则返回下标,不存在返回-1
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 addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
//加锁
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
//不相等说明其他线程调用getArray
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++)
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();
}
}
3.获取元素
get(int index)
public E get(int index) {
//直接获取对应索引元素
return get(getArray(), index);
}
private E get(Object[] a, int index) {
return (E) a[index];
}
4.删除元素
remove(int index)
public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();
//删除对应索引元素,把数组长度-1
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();
}
}
remove(Object 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 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;
}
//同remove(int index)
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();
}
}
- CopyOnWriteArrayList使用ReentrantLock重入锁加锁,保证线程安全;
- CopyOnWriteArrayList的写操作都要先拷贝一份新数组,在新数组中做修改,修改完了再用新数组替换老数组,所以空间复杂度是O(n),性能比较低下;
- CopyOnWriteArrayList的读操作支持随机访问,时间复杂度为O(1);
- CopyOnWriteArrayList采用读写分离的思想,读操作不加锁,写操作加锁,且写操作占用较大内存空间,所以适用于读多写少的场合;
- CopyOnWriteArrayList只保证最终一致性,不保证实时一致性;