java并发之CopyOnWirteArrayList
CopyOnWirteArrayList的实现
它用了ReentrantLock保证了add,set,remove操作的安全,同时使用volatile定义内部数组保证了可见性,
之所以叫CopyOnWrite就是因为很多方法都是通过Array.copy或者System.arraycopy,操作中有数组的
拷贝,所以写的操作效率很低
例子
package javalearn.javabase.concurrent;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
@Slf4j
public class CopyWriteOnArrayListTest {
private static int capcity = 5;
private static List<String> list = new CopyOnWriteArrayList<String>();
//private static List<String> list = new ArrayList<>();会抛出异常ConcurrentModificationException
public static void main(String[] args) {
InnerThread t1 = new InnerThread();
InnerThread t2 =new InnerThread();
t1.start();
t2.start();
}
static class InnerThread extends Thread {
@Override
public void run() {
for (int i = 0; i < capcity; i++) {
list.add(String.valueOf(i));
iteratorList(list);
}
}
}
public static void iteratorList(List list){
Iterator iterator =list.iterator();
while(iterator.hasNext()){
iterator.next();
}
}
}