collection中的fast-fail机制
摘自[java Generics and Collections]
The policy of the iterators for the Java 2 collections is to fail fast, as described in Section 11.1: every time they access the backing collection, they check it for structural modification (which, in general, means that elements have been added or removed from the collection). If they detect structural modification, they fail immediately, throwing ConcurrentModificationException rather than continuing to attempt to iterate over the modified collection with unpredictable results. Note that this fail-fast behavior is provided to help find and diagnose bugs; it is not guaranteed as part of the collection contract
在Java 2中的集合中的iterator
使用的是fail fast
机制,在Section11.1中描述:在每次访问collection时,迭代器会校验该collection的结构是否被修改过(一般来说,就是collection中的元素被添加或者被移除),如果检测到collection的结构被修改过,迭代器立即失败,抛出ConcurrentModificationException
异常,而不是继续尝试去迭代遍历这个被修改过的collection从而返回不可预测的结果。注意,这个fail fast
机制是提供用来帮助和诊断bugs,它不能作为保证集合的一种约定