容器中迭代器的fail-fast机制
容器中迭代器的fail-fast机制
研究过ArrayList或HashMap源码的朋友就会发现,这两个类中都提到了fail-fast机制
fail-fast机制理解
ArrayList或HashMap集合在迭代时,机制如果有其他线程在修改,会触发迭代器的fail-fast,从而抛ConcurrentModificationException。
fail-fast机制实现原理
- ArrayList或HashMap(一些是非线程安全的集合类)都是通过modCount字段来记录ArrayList或HashMap在结构上(modifies the map structurally)被修改的次数,从而实现在遍历的时候通过判断modCount的值是否相等来判断遍历过程中是否存在并发修改问题。
- 如果ArrayList或HashMap实例在结构上(modifies the map structurally)被修改了,比如add、remove 等操作,就会modCount++。
例如
在迭代一个ArrayList前,已经插入了3个元素,此时modCount = 3,expectedModCount就会被初始化为modCount即3。如果在遍历过程中,调用了remove方法,modCount + 1,则 throw new ConcurrentModificationException()。
add中modCount
add方法里面调用了ensureCapacityInternal,ensureCapacityInternal调用ensureExplicitCapacity方法里面有modCount++
remove中modCount
remove方法里面调用fastRemove,fastRemove里面有modCount++