ConcurrentModificationException


As the name indicates, this exception is thrown when two objects are modifying a DS (like Vector or ArrayList) concurrently (at the same time when an operation, like iteration, is going on).

Observe, the following code.

import java.util.*;
public class IteratorDemo
{
  public static void main(String args[])
  {
    ArrayList al1 = new ArrayList ();
    al1.add("Raju");  
    al1.add("Reddy");
    al1.add("Rao");
    al1.add("Ratnakar");

    ListIterator it1 = al1.listIterator();

    while(it1.hasNext())
    {
      System.out.print(it1.next() + " ");
      it1.add("Setty");
      al1.add("Goud");
   }
  }
}

ConcurrentModificationException

Observe, in the while loop, both ListIterator (with it1) and ArrayList (with al1) are adding the elements to the ArrayList concurrently while iteration is going on. This is not allowed.

Fail-Fast

Observe the following code. Even it is an exception.

       while(it1.hasNext())
       {
         System.out.print(it1.next() + " ");
         al1.add("Goud");
       }
 

The iterators of Iterator and ListIterator are fail-fast. While the iteration is going on, the programmer cannot make structural changes (like addition, removal or replacing etc.) on the ArrayList object that returned the ListIterator object. If happens, JVM throws ConcurrentModificationException due to non-deterministic behavior. But while iteration is going on, Iterator or ListIterator object can do the changes in the ArrayList. That is, following works fine.

       while(it1.hasNext())
       {
         System.out.print(it1.next() + " ");
         it1.add("Goud");
       }

But the Enumeration object returned by the Vector is not fail-fast.

To be more precise, even the following code throws ConcurrentModificationException.

      ListIterator it1 = al1.listIterator();
      al1.add("Goud");
      while(it1.hasNext())
      {
        System.out.print(it1.next() + " ");
        it1.add("Setty");
      }

When once ListIterator object is created, operations on ArrayList object al1 cannot be done. The above code also throws ConcurrentModificationException.

3 thoughts on “ConcurrentModificationException”

Leave a Comment

Your email address will not be published.