jdk版本:1.8.0_77
參考文檔:jdk 1.8 docs
CopyOnWriteArrayList類圖
CopyOnWriteArrayList繼承關(guān)系
CopyOnWriteArrayList特點
- ArrayList線程安全的擴展版本,所有改變集合的操作(add,set...)需要首先對當(dāng)前數(shù)組制作一份拷貝。
@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"));
}
運行結(jié)果:
[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);//創(chuàng)建新的數(shù)組對象
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
由此可見,每次添加操作集合中的數(shù)組對象不再是操作之前的數(shù)組對象杠览。
- 每次修改拷貝新版本花費巨大动雹,在讀多寫少(相比Vector中方法使用synchronized同步鎖)情況下它是更好的選擇方案靠柑。
@Test
public void testCompareCopyOnWriteArrayListandSynchronizedMap() throws InterruptedException {
ArrayList<Integer> 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);
}
運行結(jié)果:
sychronized list run time:12125628
copyonwritearraylist run time:3324206
在設(shè)置64個線程(本機其實是雙核四線程...)執(zhí)行讀取讀取操作躁染,CopyOnWriteArrayList比加鎖的List速度上快了有4倍之多膝捞,在多線程下共享集合(集合不常改變)最好使用CopyOnWriteArrayList瀑凝。
- 在創(chuàng)建迭代器時復(fù)制一份數(shù)組拷貝(快照)序芦,在迭代期間數(shù)組不會被改變,調(diào)用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();
}
運行結(jié)果:
java.lang.UnsupportedOperationException
at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(CopyOnWriteArrayList.java:1176)
public void remove() {//COWIterator
throw new UnsupportedOperationException();
}
之所以這樣設(shè)置是因為CopyOnWrite必須在改變數(shù)組是先制作一份拷貝射窒,所以迭代中不允許移除藏杖、變更元素。
- null也可以保存在對象中脉顿。
@Test
public void testNull() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList<>();
copyOnWriteArrayList.add(null);
}
- 內(nèi)存一致性原則:一個線程向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();
}
運行結(jié)果:
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
- 為了避免每次添加操作都新建一個數(shù)組對象,每次添加時添加一個集合而不是單個對象艾疟。
@Test
public void testBetterWay() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList<>();
copyOnWriteArrayList.add("test1");//bad
//good
ArrayList<Object> list = new ArrayList<>();
list.add("test2");
list.add("test3");
copyOnWriteArrayList.addAll(list);
}