为何此处会抛出java.util.ConcurrentModificationException异常?
为什么这段Java代码会抛出ConcurrentModificationException?
先看你运行的代码:
class test { private static Set <Integer> list_of_files = new HashSet<Integer>(); private static Iterator i = list_of_files.iterator(); public static void main(String[] args) { Random random = new Random(); while(list_of_files.size()<= 15) { list_of_files.add(random.nextInt(40)); } int fist = (Integer)i.next(); } }
这段代码会抛出java.util.ConcurrentModificationException,但把Iterator声明移到main函数内就不会出现异常,原因如下:
核心原因:迭代器创建时机与集合修改时机不匹配
- 当
Iterator作为静态成员变量时,它会在类加载阶段就被初始化,此时list_of_files还是一个空的HashSet。 - 后续在
main方法中,你通过add操作多次修改了集合的结构(添加元素),而Java集合的迭代器采用**快速失败(fail-fast)**机制:迭代器一旦创建,就会记录集合的结构状态,若后续集合结构被修改(非迭代器自身的remove方法),迭代器执行next()等操作时就会检测到这个变化,直接抛出异常,防止迭代过程中集合状态不一致导致的问题。
移到main函数内无异常的原因
把Iterator的声明放在main方法内时,是在所有集合添加操作完成之后才创建迭代器的。此时集合的结构已经稳定,迭代器基于当前完整的集合状态初始化,后续调用next()时不会检测到结构修改,因此不会抛出异常。
内容的提问来源于stack exchange,提问作者Aurorachilles
相关产品推荐
相关产品推荐

