0

I understand that the array list produces concurrent modification exception when we try to perform (add/remove) on the list, while iterating over the list.

For example, the following method should throw Concurrent Modification Exception as I try to remove a item, while iterating.

public static void testMe() {
    inputList = new ArrayList<String>();
    inputList.add("1");
    inputList.add("2");
    inputList.add("3");

 // Try comment the above insertion and uncomment this and run
 // for (int i = 0; i < 5; i++) {
 //     inputList.add(""+i);
 // }

    System.out.println("List Size:" + inputList.size());
    Iterator<String> iterator = inputList.iterator();
    while (iterator.hasNext()) {
        String value = (String) iterator.next();
        if (value.equals("2")) {
            inputList.remove(value);
            System.out.println("remvoing 2");
        }
    }
    System.out.println("List Size:" + inputList.size());
}

Strangely I don't get one. But if I insert items using a for loop, the exception is thrown. I wonder why this is not happening earlier?

SaravMani
  • 83
  • 8
  • Sorry.!! It is indeed a duplicate question.. I should have looked beyond what was suggested by stack overflow while writing this question. http://stackoverflow.com/questions/29723458/why-doesnt-this-code-throw-a-concurrentmodificationexception. – SaravMani May 04 '15 at 01:51

1 Answers1

0

I misread the question when I wrote my original accepted answer but cannot delete this since it's accepted so I'll edit this to summarize another accepted answer here: https://stackoverflow.com/a/29723542/1630906

As a general rule, ConcurrentModificationExceptions are thrown when the modification is detected, not caused.

Thus, as ConcurrentModificationExceptions are thrown when a call to next() detects a that a modification has been made, this scenario narrowly avoids such an exception.

So just like the asker themselves noted in the comments:

If the list had 4 elements and if you try to remove a element in the second iteration then you will get concurrent modification.

Community
  • 1
  • 1
ekuusela
  • 5,034
  • 1
  • 25
  • 43
  • In addition to @ekuusela answer, My colleague clearly explained the issue in my example. Generally, concurrent modifications will be caught only during the call to next(). In my example the list had 3 items and during the second iteration, a item had been removed and then hasNext() will return false which will exit the while loop (next() is not called). If the list had 4 elements and if you try to remove a element in the second iteration then you will get concurrent modification. – SaravMani May 04 '15 at 02:01