2. 核心作用:Fail-Fast 机制
modCount 是 Fail-Fast(快速失败) 机制的核心,用于在以下场景快速检测并发修改:
场景 1:单线程迭代时修改集合
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> it = list.iterator();
list.add("D"); // 直接修改集合,modCount++
it.next(); // 迭代时检查 modCount,抛出 ConcurrentModificationException
场景 2:多线程并发修改
List<String> list = new ArrayList<>(Arrays.asList("A", "B"));
new Thread(() -> list.add("C")).start(); // 线程修改集合,modCount++
Iterator<String> it = list.iterator(); // 迭代器保存当前 modCount
it.next(); // 检查 modCount 是否变化,若变化则抛出异常
3. 实现原理
迭代器内部记录 expectedModCount
每个迭代器在创建时,会保存当前集合的 modCount 到 expectedModCount 字段。在迭代过程中,每次操作前会检查两者是否一致:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
触发异常的条件
- 若通过集合自身的方法修改结构(如
add()、remove()),modCount++,但迭代器的expectedModCount未更新。 - 若通过迭代器自身的方法修改结构(如
Iterator.remove()),会同步更新expectedModCount和modCount,避免异常。