主要谈下fail-fast机制。
fail-fast机制是一种迭代器在迭代集合的时候,不允许对集合的结构发生改变,如果改变,那么就报错。并发修改异常ConcurrentModificationException。
private class Itr implements Iterator<E> {
int cursor; // 返回下一个元素的位置
int lastRet = -1; // 返回最后一个元素的位置。-1表示没有
//expectedModCount 是期望值。也就是集合的期望修改的值。ArrayList每次元素增加或者减少都会变化modCount。
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();
}
}
//检查如果modCount!=expectedModCount。就开始抛出异常
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}