《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
-
{@link ConcurrentModificationException}. Thus, in the face of
-
concurrent modification, the iterator fails quickly and cleanly, rather
-
than risking arbitrary, non-deterministic behavior at an undetermined
-
time in the future. The {@link Enumeration Enumerations} returned by
-
the {@link #elements() elements} method are not fail-fast.
-
Note that the fail-fast behavior of an iterator cannot be guaranteed
-
as it is, generally speaking, impossible to make any hard guarantees in the
-
presence of unsynchronized concurrent modification. Fail-fast iterators
-
throw {@code ConcurrentModificationException} on a best-effort basis.
-
Therefore, it would be wrong to write a program that depended on this
-
exception for its correctness: the fail-fast behavior of iterators
-
should be used only to detect bugs.
翻译
由iterator()和listIterator()返回的迭代器是fail-fast的。在于程序在对list进行迭代时,某个线程对该collection在结构上对其做了修改,这时迭代器就会抛出ConcurrentModificationException异常信息。因此,面对并发的修改,迭代器快速而干净利落地失败,而不是在不确定的情况下冒险。由elements()返回的Enumerations不是fail-fast的。需要注意的是,迭代器的fail-fast并不能得到保证,它不能够保证一定出现该错误。一般来说,fail-fast会尽最大努力抛出ConcurrentModificationException异常。因此,为提高此类操作的正确性而编写一个依赖于此异常的程序是错误的做法,正确做法是:ConcurrentModificationException 应该仅用于检测 bug。
大意为在遍历一个集合时,当集合结构被修改,很有可能会抛出Concurrent Modification Exception。为什么说是很有可能呢?从下文中我们可以知道,迭代器的remove操作(注意是迭代器的remove方法而不是集合的remove方法)修改集合结构就不会导致这个异常。
看到这里我们就明白了,fail-fast 机制是java容器(Collection和Map都存在fail-fast机制)中的一种错误机制。在遍历一个容器对象时,当容器结构被修改&