Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an Iterator throw ConcurrentModificationException on add

Tags:

java

iterator

How does Iterator throw ConcurrentModificationException when we are adding some object after current node or removing some object after current node. Does Iterator maintain a copy or reference to the underlying collection?

like image 992
banjara Avatar asked Jun 12 '12 15:06

banjara


People also ask

Does iterator throw a ConcurrentModificationException?

ConcurrentModificationException is not thrown by Iterator. remove() because that is the permitted way to modify an collection while iterating.

What causes ConcurrentModificationException?

What Causes ConcurrentModificationException. The ConcurrentModificationException generally occurs when working with Java Collections. The Collection classes in Java are very fail-fast and if they are attempted to be modified while a thread is iterating over it, a ConcurrentModificationException is thrown.

Does stream throw ConcurrentModificationException?

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException .


2 Answers

The iterator maintains a reference to the underlying collection. If you add or remove an element, the iterator might be left at an impossible index, or the collection might change "out from underneath" the iterator.

Therefore, instead of letting the iterator get corrupted without letting you know, most collections do the courtesy of throwing a ConcurrentModificationException when you try to modify the collection while iterating, so you don't wind up with unpredictably corrupted iterators.

like image 116
Louis Wasserman Avatar answered Oct 04 '22 01:10

Louis Wasserman


By contract, you are not allowed to modify the collection while iterating over it (except by using Iterator.remove() et al).

Instead of randomly failing when you do this, the collection is nice enough to keep track of how many times it's been modified, and throw ConcurrentModificationException when it detects concurrent modification.

like image 28
NPE Avatar answered Oct 04 '22 00:10

NPE