Search code examples
javaconcurrentmodification

Why im not getting concurrent modification exception during update of collection element?


I just read that concurrent modification exception would occur if we add, remove,or update collection after calling iterator method

I understand why adding and removing a collection element would cause concurrent modification exception, but why updating should cause concurrent modification? after all we dont change anything structurally while updating an element.

for example the below code is from arraylist implementation

public E set(int index, E element) {
    rangeCheck(index);

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

we dont update the variable "modcount" which is actually used for checking concurrent modification.

i also tried with my custom code:

public static void main(String[] args) {
    ArrayList l= new ArrayList();
    l.add("string");
    l.add(3);
    Iterator it=l.iterator();
    Object o=it.next();
    l.set(0, "element");
    l.remove(o);
    //l.add(7);
    //it.next();

    System.out.println(it.next());
    System.out.println(l.get(0));
    int i;
    System.out.println(j+" "+j);
}

this doesn't throw concurrent modifcation exception either.

may i know why?


Solution

  • why updating should cause concurrent modification?

    If by "updating" you mean calling the set method, it won't cause concurrent modification. Setting the value of an element in the List is not a structural modification, and therefore doesn't cause ConcurrentModificationException when performed during iteration.

    Quotes from the ArrayList Javadoc:

    A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification ...

    The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.