Java深入学习31:ArrayList并发异常以及解决方案
先看一个ArrayList多线程的下的案例。
该案例会出现一些异常的情况,,期中有两个异常需要留意
public classArrayListConcurrentTest {public static voidmain(String[] args) {
List list = new ArrayList<>();for (int i = 0; i < 10; i++) {new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(Thread.currentThread().getName()+ "\t" +list);
}).start();
}
}
}----------------------------------------日志1---------------------------------------------
Thread-2 [null, 6237f3be]
Thread-0[null, 6237f3be]
Thread-1[null, 6237f3be]
main[null, 6237f3be]
----------------------------------------日志2---------------------------------------------
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at java.util.AbstractCollection.toString(AbstractCollection.java:461)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at colleaction.ArrayListConcurrentTest.lambda$main$0(ArrayListConcurrentTest.java:22)
at java.lang.Thread.run(Thread.java:748)
1- 出现了list元素为null和元素"丢失"的情况,这个不是我们期望的。
原因:首先 ArrayList 的 add 方法不是线程安全的。对于其中的 elementData[size++] = e操作,分为size++和数组赋值两步操作,假设线程1执行了size++后(此时size=1,index=0),CPU时间片挂起;线程2进来执行size++和数组赋值(此时size=2,index=1);线程1获取到CPU时间片,执行数组赋值(此时size=2,index=1);那么久出现了线程1和线程2同时对index=1进行了赋值,并导致index=0没有被赋值的情况
##ArrayList类public booleanadd(E e) {
ensureCapacityInternal(size+ 1); //Increments modCount!!
elementData[size++] = e;return true;
}private void ensureCapacityInternal(intminCapacity) {if (elementData ==DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity=Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}private void ensureExplicitCapacity(intminCapacity) {
modCount++;//overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}private void grow(intminCapacity) {//overflow-conscious code
int oldCapacity =elementData.length;int newCapacity = oldCapacity + (oldCapacity >> 1);if (newCapacity - minCapacity < 0)
newCapacity=minCapacity;if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity=hugeCapacity(minCapacity);//minCapacity is usually close to size, so this is a win:
elementData =Arrays.copyOf(elementData, newCapacity);
}
2- 出现ConcurrentModificationExceptionThread异常
原因:我们在执行日志输出 System.out.println(Thread.currentThread().getName() + "\t" +list) 时;使用的ArratLIst的Iterator的迭代器获取list的每个元素;每迭代会实例化一个Iterator对象,其中有个变量预期修改次数 expectedModCount 默认等于list的修改次数 modCount;每次使用Iterator.next()迭代遍历list时,都需要进行checkForComodification判断(判断modCount != expectedModCount);多线程下,会出现一种情况,线程1在遍历list;与此同时,线程2在修改list(导致modCount++);那么线程1在便利获取元素时会出现checkForComodification失败的情况,此时抛出ConcurrentModificationException异常。
##ArrayList类public Iteratoriterator() {return newItr();
}
##ArrayList类的内部类Itrprivate class Itr implements Iterator{int expectedModCount =modCount;public booleanhasNext() {return cursor !=size;
}
@SuppressWarnings("unchecked")publicE next() {
checkForComodification();
......
}final voidcheckForComodification() {if (modCount !=expectedModCount)throw newConcurrentModificationException();
}
}
如何处理ArrayList异常
1- 使用Vector;
Vector类整体来说是线程安全;因为Vector对add以及内部的Iterator.next方法都加了 synchronized 关键字;其中add方法锁的是Vector示例对象,内部类Iterator.next()中锁的是Vector.this(其实就是Vector类当前的实例);所以这里add()方法和Iterator.next()方法互斥,不会出现ConcurrentModificationException异常。
##Vector类public synchronized booleanadd(E e) {
modCount++;
ensureCapacityHelper(elementCount+ 1);
elementData[elementCount++] =e;return true;
}
##Vector类中的内部类Itr 类private class Itr implements Iterator{int expectedModCount =modCount;publicE next() {synchronized (Vector.this) {
checkForComodification();int i =cursor;if (i >=elementCount)throw newNoSuchElementException();
cursor= i + 1;return elementData(lastRet =i);
}
}
}
2- 使用Collections.synchronizedList(new ArrayList<>())
3- 使用 CopyOnWriteArrayList
END