CopyOnWriteArrayList
是juc
提供的一个线程安全的集合
示例代码
public class ArrayListTest {
private static ArrayList<Integer> arrayList;
private static CopyOnWriteArrayList<Integer> copyOnWriteArrayList;
public static void main(String[] args) {
copyOnWriteArrayList = new CopyOnWriteArrayList<>();
for (int i= 0 ; i < 10 ;i++){
new Thread(()->{
for (int j = 0 ; j < 3 ; j++){
copyOnWriteArrayList.add(j);
}
}).start();
}
copyOnWriteArrayList.forEach(x->{
System.out.println(x);
});
System.out.println(copyOnWriteArrayList.get(0));
System.out.println(JSON.toJSONString(copyOnWriteArrayList));
}
}
new CopyOnWriteArrayList<>();
private transient volatile Object[] array;
public CopyOnWriteArrayList() {
setArray(new Object[0]);
}
final void setArray(Object[] a) {
array = a;
}
实例化其实就相当简单,内部定义了一个Object[]
存储元素,无参构造防范,初始化了一个空的Object
数组,然后这个数组属性array
用了两个关键字修饰,一个是transient
,忽略其序列化,另一个是volatile
,保证可见性
add()
这个类型的特性都体现在这个方法了,它依靠ReentrantLock
来保证线程安全,每次增加一个元素,都是通过Arrays.copyOf
方法弄出一个长度+1的新数组,然后修改array属性
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();
}
}
从copyOf
方法可以看出,本质还是使用的System.arraycopy
方法在数组之间复制元素
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
通过索引取元素也是相当朴素
可以看到获取元素是完全无锁化的
public E get(int index) {
return get(getArray(), index);
}
private E get(Object[] a, int index) {
return (E) a[index];
}
总结
总的来说就是用来在多线程场景下代替ArrayList
,写的时候多少需要考虑下copy带来的性能损耗,但是读的性能已经被优化到极致了,它写的时候,通过加锁做复制和替换,但是只有在替换这个操作进行的一瞬间才会对读操作产生影响,所谓替换就是改变属性array
的指针指向,它使用了volatile
修饰,当指针重新指向的时候,保证读取操作的可见性,这个操作耗时都可以忽略不记了,所以这个集合主要还是适用于读远多于写的场景,如果写的操作并不低频,建议不要使用add()
方法添加元素,而是使用addAll()
public boolean addAll(Collection<? extends E> c) {
Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
if (cs.length == 0)
return false;
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
if (len == 0 && (c.getClass() == CopyOnWriteArrayList.class ||
c.getClass() == ArrayList.class)) {
setArray(cs);
} else {
Object[] newElements = Arrays.copyOf(elements, len + cs.length);
System.arraycopy(cs, 0, newElements, len, cs.length);
setArray(newElements);
}
return true;
} finally {
lock.unlock();
}
}
看个例子:多个线程生产元素添加到copyOnWriteArrayList
中
public static void main(String[] args) {
copyOnWriteArrayList = new CopyOnWriteArrayList<>();
long start = System.currentTimeMillis();
CountDownLatch latch = new CountDownLatch(30);
for (int i= 0 ; i < 30 ;i++){
new Thread(()->{
for (int j = 0 ; j < 30000 ; j++){
copyOnWriteArrayList.add(j);
}
latch.countDown();
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(copyOnWriteArrayList.size());
long end = System.currentTimeMillis();
System.out.println("耗时:"+ (end-start) );
}
public static void main(String[] args) {
copyOnWriteArrayList = new CopyOnWriteArrayList<>();
long start = System.currentTimeMillis();
CountDownLatch latch = new CountDownLatch(30);
for (int i= 0 ; i < 30 ;i++){
new Thread(()->{
ArrayList<Integer> temp = new ArrayList<>(300);
for (int j = 0 ; j < 30000 ; j++){
temp.add(j);
}
copyOnWriteArrayList.addAll(temp);
latch.countDown();
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(copyOnWriteArrayList.size());
long end = System.currentTimeMillis();
System.out.println("耗时:"+ (end-start) );
}
借用分段的思想,降低写并发,前者需要一百多秒,而后者只需要一百毫秒。