How to avoid ConcurrentModificationException while iterating a collection in java?


When you are working with collection objects, while one thread is iterating over a particular collection object, if you try to add or remove elements from it, a ConcurrentModificationException will be thrown.

Not only that, If you are iterating a collection object, add or remove elements to it and try to iterate its contents again it is considered that you are trying to access the collection object using multiple threads and ConcurrentModificationException is thrown.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Iterator;
public class OccurenceOfElements {
   public static void main(String args[]) {
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println("Contents of the array list (first to last): ");
      Iterator<String> it = list.iterator();
      while(it.hasNext()) {
         System.out.print(it.next()+", ");
      }
      //list.remove(3);
      list.add(3, "Hadoop");
      while(it.hasNext()) {
         System.out.print(it.next()+", ");
      }
   }
}

Output

Contents of the array list (first to last):
JavaFX, Java, WebGL, OpenCV, Exception in thread "main"
java.util.ConcurrentModificationException
   at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
   at java.util.ArrayList$Itr.next(Unknown Source)
   at sample.OccurenceOfElements.main(OccurenceOfElements.java:23)

To resolve this while accessing collection objects from multiple threads use synchronized block or method and, if you are modifying data while retrieving it, get the Iterator object again after modifying the data.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Iterator;
public class OccurenceOfElements {
   public static void main(String args[]) {
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println("Contents of the array list (first to last): ");
      Iterator<String> it = list.iterator();
      while(it.hasNext()) {
         System.out.print(it.next()+". ");
      }
      list.remove(3);
      System.out.println("");
      System.out.println("Contents of the array list after removal: ");
      it = list.iterator();
      while(it.hasNext()) {
         System.out.print(it.next()+". ");
      }
   }
}

Output

Contents of the array list (first to last):
JavaFX. Java. WebGL. OpenCV.
Contents of the array list after removal:
JavaFX. Java. WebGL.
raja
Published on 15-Oct-2019 10:34:40
Advertisements