线程安全的 List 集合有什么?
CopyOnWriteArrayList 的特点以及使用场景?
-
CopyOnWriteArrayList 简介
-
CopyOnWriteArrayList 源码分析(Android SDK 25)
-
底部实现
-
读取操作
-
修改操作
-
迭代器
-
-
CopyOnWriteArrayList 源码 JDK8 有什么不同
-
总结
-
优缺点
-
CopyOnWriteArrayList 简介
-
Vector
-
CopyOnWriteArrayList
public class CopyOnWriteArrayList<E> implements List<E>, RandomAccess, Cloneable, Serializable {
//...
}
CopyOnWriteArrayList 源码分析(Android SDK 25)
底部实现
private transient volatile Object[] elements;
public CopyOnWriteArrayList() {
elements = EmptyArray.OBJECT;
}
@SuppressWarnings("unchecked")
public CopyOnWriteArrayList(Collection<? extends E> collection) {
this((E[]) collection.toArray());
}
public CopyOnWriteArrayList(E[] array) {
this.elements = Arrays.copyOf(array, array.length, Object[].class);
}
读取操作
public int size() {
return elements.length;
}
@SuppressWarnings("unchecked")
public E get(int index) {
return (E) elements[index];
}
public boolean isEmpty() {
return elements.length == 0;
}
修改操作
public synchronized boolean add(E e) {
Object[] newElements = new Object[elements.length + 1];
System.arraycopy(elements, 0, newElements, 0, elements.length);
newElements[elements.length] = e;
//这步执行前,其他线程访问的就是旧数据
elements = newElements;
return true;
}
public synchronized void add(int index, E e) {
Object[] newElements = new Object[elements.length + 1];
System.arraycopy(elements, 0, newElements, 0, index);
newElements[index] = e;
System.arraycopy(elements, index, newElements, index + 1, elements.length - index);
elements = newElements;
}
public synchronized E set(int index, E e) {
Object[] newElements = elements.clone();
@SuppressWarnings("unchecked")
E result = (E) newElements[index];
newElements[index] = e;
elements = newElements;
return result;
}
public synchronized E remove(int index) {
@SuppressWarnings("unchecked")
E removed = (E) elements[index];
removeRange(index, index + 1);
return removed;
}
public synchronized boolean remove(Object o) {
int index = indexOf(o);
if (index == -1) {
return false;
}
remove(index);
return true;
}
private void removeRange(int from, int to) {
Object[] newElements = new Object[elements.length - (to - from)];
System.arraycopy(elements, 0, newElements, 0, from);
System.arraycopy(elements, to, newElements, from, elements.length - to);
elements = newElements;
}
迭代器
public Iterator<E> iterator() {
Object[] snapshot = elements; //读取的是快照
return new CowIterator<E>(snapshot, 0, snapshot.length);
}
//读取的也是快照,并且不支持 remove()
public ListIterator<E> listIterator(int index) {
Object[] snapshot = elements;
if (index < 0 || index > snapshot.length) {
throw new IndexOutOfBoundsException("index=" + index + ", length=" + snapshot.length);
}
CowIterator<E> result = new CowIterator<E>(snapshot, 0, snapshot.length);
result.index = index;
return result;
}
/**
* Equivalent to {@code listIterator(0)}.
*/
public ListIterator<E> listIterator() {
Object[] snapshot = elements;
return new CowIterator<E>(snapshot, 0, snapshot.length);
}
static class CowIterator<E> implements ListIterator<E> {
private final Object[] snapshot;
private final int from;
private final int to;
private int index = 0;
CowIterator(Object[] snapshot, int from, int to) {
this.snapshot = snapshot;
this.from = from;
this.to = to;
this.index = from;
}
public void add(E object) {
throw new UnsupportedOperationException();
}
//...
public void remove() {
throw new UnsupportedOperationException();
}
public void set(E object) {
throw new UnsupportedOperationException();
}
//...
}
CopyOnWriteArrayList 源码 JDK8 有什么不同
public class CopyOnWriteArrayList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
private static final long serialVersionUID = 8673264195747942595L;
//锁住所有修改操作
final transient ReentrantLock lock = new ReentrantLock();
//只能被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);
}
public CopyOnWriteArrayList(E[] toCopyIn) {
setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
}
public int size() {
return getArray().length;
}
public boolean isEmpty() {
return size() == 0;
}
private E get(Object[] a, int index) {
return (E) a[index];
}
public E get(int index) {
return get(getArray(), index);
}
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();
}
}
-
synchronized 无法中断一个正在等候获得锁的线程,也无法通过投票得到锁
-
ReentrantLock 拥有与 synchronized 相同的并发性和内存语义,但是添加了类似锁投票、定时锁等候和可中断锁等候的一些特性
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();
}
}
总结
-
底部实现(这里是数组) volatile 修饰,保证一致性
-
写时复制,写完更新引用
优缺点
-
可以在多线程环境下操作 List
-
读的效率很高
-
读的可能不是最新值
-
每次写需要创建个新数组,占用额外内存