jdk版本:1.8.0_77
参考文档:jdk 1.8 docs
CopyOnWriteArrayList类图
CopyOnWriteArrayList特点
- ArrayList线程安全的扩展版本,所有改变集合的操作(add,set...)需要首先对当前数组制作一份拷贝。
@Test
public void testAdd() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList<>();
copyOnWriteArrayList.add("1");
System.out.println(ReflectUtilss.getFieldValue(copyOnWriteArrayList, "array"));
copyOnWriteArrayList.add("2");
System.out.println(ReflectUtilss.getFieldValue(copyOnWriteArrayList, "array"));
copyOnWriteArrayList.add("3");
System.out.println(ReflectUtilss.getFieldValue(copyOnWriteArrayList, "array"));
}
运行结果:
[Ljava.lang.Object;@aec6354
[Ljava.lang.Object;@1c655221
[Ljava.lang.Object;@58d25a40
源代码:
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();
}
}
由此可见,每次添加操作集合中的数组对象不再是操作之前的数组对象。
- 每次修改拷贝新版本花费巨大,在读多写少(相比Vector中方法使用synchronized同步锁)情况下它是更好的选择方案。
@Test
public void testCompareCopyOnWriteArrayListandSynchronizedMap() throws InterruptedException {
ArrayList arrayList = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
arrayList.add(i);
}
List sychronizedList = Collections.synchronizedList(arrayList);
List copyOnWriteArrayList = new CopyOnWriteArrayList<>(arrayList);
RunTest[] runTests = new RunTest[64];
for (int i = 0; i < runTests.length; i++) {
runTests[i] = new RunTest(sychronizedList);
}
for (int i = 0; i < runTests.length; i++) {
runTests[i].start();
}
for (int i = 0; i < runTests.length; i++) {
runTests[i].join();
}
System.out.println(RunTest.TIME);
RunTest.TIME = 0l;
for (int i = 0; i < runTests.length; i++) {
runTests[i] = new RunTest(copyOnWriteArrayList);
}
for (int i = 0; i < runTests.length; i++) {
runTests[i].start();
}
for (int i = 0; i < runTests.length; i++) {
runTests[i].join();
}
System.out.println(RunTest.TIME);
}
运行结果:
sychronized list run time:12125628
copyonwritearraylist run time:3324206
在设置64个线程(本机其实是双核四线程...)执行读取读取操作,CopyOnWriteArrayList比加锁的List速度上快了有4倍之多,在多线程下共享集合(集合不常改变)最好使用CopyOnWriteArrayList。
- 在创建迭代器时复制一份数组拷贝(快照),在迭代期间数组不会被改变,调用remove、set、add方法抛出UnsupportedOperationException异常。
@Test
public void testIterator() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList<>();
//COWIterator
Iterator iterator = copyOnWriteArrayList.iterator();
//throw UnsupportedOperationException
iterator.remove();
}
运行结果:
java.lang.UnsupportedOperationException
at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(CopyOnWriteArrayList.java:1176)
public void remove() {//COWIterator
throw new UnsupportedOperationException();
}
之所以这样设置是因为CopyOnWrite必须在改变数组是先制作一份拷贝,所以迭代中不允许移除、变更元素。
- null也可以保存在对象中。
@Test
public void testNull() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList<>();
copyOnWriteArrayList.add(null);
}
- 内存一致性原则:一个线程向CopyOnWriteArrayList添加对象动作一定happen-before在其之后另一个线程从CopyOnWriteArrayList移除对象。
@Test
public void testHappenBefore() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList<>();
copyOnWriteArrayList.add("test");
Thread threadB = new Thread() {
@Override
public void run() {
try {
Thread.sleep(5000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println("thread add before:" + ReflectUtilss.getFieldValue(copyOnWriteArrayList, "array"));
copyOnWriteArrayList.remove("test");
System.out.println("thread add before:" + ReflectUtilss.getFieldValue(copyOnWriteArrayList, "array"));
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println("thread B remove elements");
}
};
threadB.start();
System.out.println("main add before:" + ReflectUtilss.getFieldValue(copyOnWriteArrayList, "array"));
copyOnWriteArrayList.add("test");//thread A add elements
System.out.println("main add after:" + ReflectUtilss.getFieldValue(copyOnWriteArrayList, "array"));
threadB.join();
}
运行结果:
main add before:[Ljava.lang.Object;@aec6354
main add after:[Ljava.lang.Object;@1c655221
thread add before:[Ljava.lang.Object;@1c655221
thread add before:[Ljava.lang.Object;@24b8368a
- 为了避免每次添加操作都新建一个数组对象,每次添加时添加一个集合而不是单个对象。
@Test
public void testBetterWay() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList<>();
copyOnWriteArrayList.add("test1");//bad
//good
ArrayList
代码