Search code examples
javahashmapiteratorconcurrenthashmap

HashMap is not synchronized then why concurrentmodification exception


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


Solution

  • 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 Maps. Collections also throw this exception when they are being modified during iteration.