产生故障原因:
一个线程正在写入,另外一个线程过来抢夺,导致数据不一致异常,并发修改异常:demo可以重现异常
增:
public class ListDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 50; i++) {
new Thread(() ->{
list.add(UUID.randomUUID().toString().substring(0,4));
System.out.println(list);
},"线程t" + i).start();
}
}
}
删:
public class ListDelDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
list.add(i);
}
for (Integer i : list) {
if(i == 8){
list.remove(i);
}else{
System.out.println(i);
}
}
}
}
//运行结果
//Exception in thread "线程t21" java.util.ConcurrentModificationException
//Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at com.navigation.qdy.controller.ListDelDemo.main(ListDelDemo.java:16)
原因解释
简单地说下原因,遍历的方式是 for 循环,在底层使用的是迭代器。
也就是说,是用Itr去遍历的,这个Itr是ArrayList实现的一个遍历接口、内部类。
但是我在删除的时候是通过ArrayList的remove方法去操作的,不是Itr内部的那个删除方法去操作的。
那么问题就来了:
ArrayList的remove方法修改的变量是继承自AbstractList的变量modCount;而Itr的remove方法修改的是自身的变量expectedModCount。这两个变量的作用都是记录修改次数的。
所以,在用ArrayList的remove方法进行删除操作以后,Itr里面的expectedModCount会与ArrayList的modCount进行比较,二者不相等,所以会报错。
源码分析
报错的是ArrayList.java里的Itr.next()和Itr.checkForComodification()。
Itr是在ArrayList的内部类,实现了Iterator接口,用于遍历:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
// prevent creating a synthetic constructor
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();//注意这里会比较
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
... ...
报错就是在Itr.next()中调用checkForComodification()以后产生的,在checkForComodification()函数中,判断了modCount和expectedModCount是否相等。如果不相等,就会抛出我们遇到的这个异常。显然,我们的报错就是因为这两个变量不相等导致的。
... ...
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
... ...
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
那这两个变量是什么含义呢?
modCount是modification count的缩写,也就是当前的ArrayList被修改的次数,这个变量是ArrayList继承自AbstractList的。
expectedModCount是expected modification count的缩写,也就是期望被修改的次数,这个变量是在内部类Itr中定义的,初始时赋值为modCount。
ok,那为什么我们的写法会导致这两个变量不一致呢?
这里要注意的是,我遍历的时候调用的是Itr.next(),但是我在循环中删除元素时,用的是ArrayList.this.remove():当然add都是同理
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
... ...
public boolean remove(Object o) {
final Object[] es = elementData;
final int size = this.size;
int i = 0;
found: {
if (o == null) {
for (; i < size; i++)
if (es[i] == null)
break found;
} else {
for (; i < size; i++)
if (o.equals(es[i]))
break found;
}
return false;
}
fastRemove(es, i);
return true;
}
private void fastRemove(Object[] es, int i) {
modCount++;
final int newSize;
if ((newSize = size - 1) > i)
System.arraycopy(es, i + 1, es, i, newSize - i);
es[size = newSize] = null;
}
... ...
list.add:
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
remove()函数会调用fastRemove()函数,使得modCount的值自增1.
然而,for循环下一次调用Itr.next(),Itr.next()调用Itr.checkForComodification()时,会发现,modCount和expectedModCount两个值不相等!因为在这个删除操作的过程中没有对expectedModCount重新赋值,所以就抛出异常了。
解决方案
改成Iterator的迭代方式,用内部类Itr的remove方法来删除,保证一致性:
class ListDelDemo{
public static void main(String[] args){
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i=0; i<20; i++){
arr.add(i);
}
for(Iterator<Integer> it=arr.iterator(); it.hasNext();){
Integer i = it.next();
if(i == 8){
it.remove();
}
else{
System.out.println(i);
}
}
}
}
每次删除的时候都让i减1
class ListDelDemo{
public static void main(String[] args){
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i=0; i<20; i++){
arr.add(i);
}
for(int i=0; i<arr.size(); i++){
if(i == 8){
arr.remove(i);
i -= 1;
}else{
System.out.println(i);
}
}
}
}
另,ArrayList 是一个查询为主的数据结构,底层是数组实现的,本身就不太适合修改频繁以及并发修改的场景。
对于频繁修改的,可以用LinkedList,对于线程安全的,可以用JUC的CopyOnWriteArrayList。
简单分析下CopyOnWriteArrayList,先看下add方法:
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();
}
}
拓展下:CopyOnWriteArrayList即写时复制容器:往容器中添加元素的时候,不直接往当前容器中Object[]添加,而是先将当前容器Object[]进行copy,复制一个新的容器Object[] newElements,然后往新的容器里Object[] newElements添加元素,添加完元素后,再将原容器的引用指向新的容器setArray(newElements);。这样做的好处是可以对copyOnWrite容器进行并发的读,而不用加锁,因为当前容器不会添加添加任何元素。所以copyOnWrite容器也是一种读写分离的思想,读和写不同的容器。