![](/img/trans.png)
[英]Multiple threads using iterator.remove() on a single collection returning fail-fast iterator
[英]If Iterators returned by HashSet, ArrayList are fail-fast, how can we use iterator remove() to remove elements from Collection
众所周知, ArrayList
, HashMap
, HashSet
等返回的Iterator
是快速失败的,但是在使用迭代器的remove()
不会抛出ConcurrentModificationException
。 怎么样?
如果在迭代集合时对其进行了修改,则快速失败迭代器将引发ConcurrentModificationException
。 但是,在使用迭代器的remove()
从ArrayList
或HashSet
删除元素时,不会引发任何ConcurrentModificationException
。 请详细说明。
谢谢
但是在使用迭代器的remove()时不会引发ConcurrentModificationException。 怎么样?
因为该行为已明确记录。
对于ArrayList
:
如果在创建迭代器之后的任何时间对列表进行结构修改,除非通过迭代器自己的
remove
或add
方法,否则迭代器将抛出ConcurrentModificationException
。
对于HashSet
:
如果在创建迭代器之后的任何时候修改了集合,则除了通过迭代器自己的
remove
方法以外,都以其他方式修改了该迭代器,则Iterator抛出ConcurrentModificationException
。
相反,如果您询问如何实现 ,那么,源代码(至少对于OpenJDK是免费的)(并且很可能直接从您的IDE中探索):)
它的实现如下:
集合包含一个private int
成员,称为modificationCount
(或类似的东西)。每次您使用修改集合的方法之一时,此modificationCount
都会增加。 在集合上创建迭代器时,迭代器会注意到该集合的modificationCount
的当前值,并且每次调用该迭代器时,请确保modificationCount
未被更改,以确保未修改集合。同时进行迭代。 如果迭代器发现modificationCount
已更改,则抛出ConcurrentModificationException
。
当您通过iterator
删除时, iterator
将避免增加集合的modificationCount
。 就这么简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.