HashMap is not supposed to be thread safe, then why do the iterators throw concurrentmodificationexception
if someone has modified the hashMap.
Also ConcurrentHashMap does not throw this exception.
Is Iterator implementation different for different datastructures or there is someone method within these data structures which throw ConcurrentModificationException
When the structure of a HashMap
is modified (i.e. entries are added or removed) while the HashMap
is being iterated over, the iterator may fail in many ways.
The ConcurrentModificationException
exception is meant to make any iterators fail-fast as a result of such modifications.
That's what the modCount
field is for :
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
This behavior is not specific to Map
s. Collection
s also throw this exception when they are being modified during iteration.