fasi-fail是Java集合的一种错误机制,当多个线程去访问同一个集合进行操作时,比如某个线程通过iterator去访问时另外一个线程去改变集合中的某个元素时就可能会抛出ConcurrentModificationException异常,产生fail-fast事件。
分析源码
fail-fast出现是在遍历集合的时候出现的,也就是对集合进行迭代的时候,对集合进行迭代的时候都是操作迭代器,集合中的内部类:(ArrayList源码)
private class Itr implements Iterator<E> {
int cursor;
int lastRet = -1;
int expectedModCount = modCount;//---------------------1
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
//………此处代码省略…………
}
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();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
在调用next,remove方法时都会调用checkForComodification方法,而这个方法会去检查一个modeCount是否和expectedModCount相等,
modCount变量在集合调用add,remove,clear方法都会自增
在迭代的时候每次都会检查这个变量是否与expectedModCount一致,因为如果是在集合中添加或者删除元素modCount的值都会发生改变。
解决方法
- 对于涉及到更改集合中元素个数的操作通通加上synchronized,或者利用Collections.synchronizedList强制他们的操作都是同步的。(全部方法加关键字synchronized)
- 使用CopyOnWriteArrayList来替换ArrayList
CopyOnWriteArrayList为什么有用
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();
}
}
//同时还有remove,set等都是对底层数组进行一次复制
那如何保证内存的一致性呢?毕竟又没有modCount去记录
看上面的 Object[] elements = getArray();
源码
final Object[] getArray() {
return array;
}
这个array用了volatile去保证内存一致性
/** The array, accessed only via getArray/setArray. */
private transient volatile Object[] array;