How does an Iterator in Java know when to throw ConcurrentModification Exception

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-28 13:13:54

A good way to answer questions like this is to look at the source code, for example the source code for ArrayList. Search for ConcurrentModificationException.

You should be able to tell that things work rather like this:

  • Collection objects have a modification count, which starts at zero and increases whenever an add or remove or similar operation occurs.
  • When an iterator object is created, we store the current modification count of the collection inside the iterator.
  • Every time the iterator is used, it checks the collection's mod count against the mod count the iterator got when it was created. If those values differ, the exception is thrown.

In your case, remove operations performed by iterator1 on the list change the structural operation count (modCount) of the list. When iterator2 is asked to remove, it sees its expectedModCount, which it received initially as 0, differing from the current mod count of the list.

It should be noted that it.remove is a special case. When an iterator does a remove itself, its expectedModCount adjusts accordingly, to keep in sync with the underlying list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!