ConcurrentModificationException while using Iterator in Java


If any particular method encountered the concurrent in a multi threaded Java environment during the resource detection then the ConcurrentModificationException might be thrown. In this process the object is a non permissible unit here.

Here is an example related to the ConcurrentModificationException in Java −

Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:000)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:000)
atcom.journaldev.ConcurrentModificationException.ConcurrentModificationExceptio
nExample.main(ConcurrentModificationExceptionExample.java:00)

For this particular process the exception is achieveable when −

  • The exception detected and iteration is in not defined in the method.

  • When the process blocked in a loop of fail fast iterator by using an internal flag called modCount.

Algorithm to ConcurrentModificationException in Java

In this possible algorithm, we are going to show you how to perform the java.util.ConcurrentModificationException in a Java environment. By using this possible algorithm we are going to build some Java syntax, by which we will explore some Java approaches further.

  • Step 1 − Start the process.

  • Step 2 − Declare and import some Java packages to run the process.

  • Step 3 − Declare a public class.

  • Step 4 − Declare a string argument.

  • Step 5 − Create an object of an array list object.

  • Step 6 − Create a new array list.

  • Step 7 − Populate the array list.

  • Step 8 − Declare a try function.

  • Step 9 − Declare a print notation for the list.

  • Step 10 − Declare an iterator class.

  • Step 11 − While go for the next value.

  • Step 12 − Add a value in the between iteration.

  • Step 13 − Print the array list with the update.

  • Step 14 − While go for the next value.

  • Step 15 − Catch the exception value.

  • Step 16 − Print the exception value.

  • Step 17 − Get the value.

  • Step 18 − Terminate the process.

Syntax to ConcurrentModificationException Using Iterator in Java

for(int i = 0; i<myList.size(); i++){
	System.out.println(myList.get(i));
	if(myList.get(i).equals("3")){
		myList.remove(i);
		i--;
		myList.add("6");
	}
}
public static void main(String[] args) {
   ArrayList<Integer> list = new ArrayList<>();
   list.add(ELEMENT);
   list.add(ELEMENT);
   list.add(ELEMENT);
   list.add(ELEMENT);
   list.add(ELEMENT);
   //Add more element if the user wants
   Iterator<Integer> it = list.iterator();
   while (it.hasNext()) {
      Integer value = it.next();
	  System.out.println("List Value:" + value);
	  if (value.equals(3))
	  list.remove(value);
   }{
      HashMap<Integer, Integer> map = new HashMap<>();
      map.put(ELEMENT 1, ELEMENT 1);
      map.put(ELEMENT 2, ELEMENT 2);
      map.put(ELEMENT 3, ELEMENT 3);
      Iterator<Integer> it = map.keySet().iterator();
      while(it.hasNext()) {
	     Integer key = it.next();
	     System.out.println("Map Value:" + map.get(key));
	     if (key.equals(SEARCH ELEMENT)){
		   map.put(ELEMENT 1, ELEMENT 4);
	     }
      }
   }
}

In this possible syntax above, we have tried to show you how to declare and run a process to achive ConcurrentModificationException in a Java environment. By using these syntax, we are heading towards some possible approaches related to the given problem statement.

Approaches to Follow

  • Approach 1 − Java Program to ConcurrentModificationException while using Iterator class, iterator.hasNext() and element addition

  • Approach 2 − Java program to illustrate the java.util.ConcurrentModificationException method by using the iterator.next() function

Approach 1: Using Iterator Class, Iterator.hasNext() and Element Addition

Use of Iterator Class Method

In this possible approach, we are going to apply the iteration method over a particular collection. We directly apply the modification process to made a few correction while we take a path of traversing. When the whole process fail to make fast iterator, at that particular point the exception occurs.

for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) {
	Integer integer = iterator.next();
	if(integer == 2) {
		iterator.remove();
	}
}

Example

//Java Program to ConcurrentModificationException while using Iterator class
import java.util.ArrayList;
import java.util.Iterator;
public class ARBRDD {
   public static void main(String[] args){
      ArrayList<Integer> list = new ArrayList<>();
      list.add(1);
      list.add(2);
      list.add(3);
      list.add(4);
      list.add(5);
      Iterator<Integer> iterator = list.iterator();
      while (iterator.hasNext()) {
         Integer value = iterator.next();
         System.out.println("value: " + value);
         if (value.equals(2)){
            System.out.println(
            "========================");
            System.out.println("removing value: "
            + value);
            System.out.println(
            "========================");
            list.remove(value);
         }
      }
   }
}

Output

value: 1
value: 2
========================
removing value: 2
========================
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
	at ARBRDD.main(ARBRDD.java:14)

Use of Iterator.hasNext() Method

In this possible approach, we are going to apply the modification process by using iterator .hasNext() when exception is raised as a modification after the iteration. We can avoid this exception when −

  • modifications once done after the iteration is over.

  • when we apply synchronized block or method.

Example

//Java Program to Avoid ConcurrentModificationException by directly using Iterator with iterator.hasNext()
import java.util.ArrayList;
import java.util.Iterator;
public class ARBRDD {
   public static void main(String[] args){
      ArrayList<Integer> list = new ArrayList<>();
      list.add(1);
      list.add(2);
      list.add(3);
      list.add(4);
      list.add(5);
      Iterator<Integer> iterator = list.iterator();
      while (iterator.hasNext()) {
         Integer value = iterator.next();
         System.out.println("value: " + value);
         if (value.equals(2)){
            System.out.println(
            "========================");
            System.out.println("removing value: "
            + value);
            System.out.println(
            "========================");
            iterator.remove();
         }
      }
   }
}

Output

value: 1
value: 2
========================
removing value: 2
========================
value: 3
value: 4
value: 5

Use of Element Addition Method in a List

In this possible approach, we are going to add some data elements in a particular data list. To achieve the ConcurrentModificationException from this process, we can add a new element to update the list and get the desired output from it.

Example

//Java program to illustrate the ConcurrentModificationException by using as an element is added during the iteration process
import java.util.Iterator;
import java.util.ArrayList;
public class ARBRDDmodificationError {
   public static void main(String args[]){
      ArrayList<String> arr
      = new ArrayList<String>();
      arr.add("ARB");
      arr.add("Bangladesh");
      arr.add("RDD");
      arr.add("India");
      try {
         System.out.println(
         "ArrayList: ");
         Iterator<String> iter
         = arr.iterator();
         while (iter.hasNext()) {
            System.out.print(iter.next()
            + "-;-");
            System.out.println(
            "\n\nTrying to add"
            + " an element in "
            + "between iteration\n");
            arr.add("Five");
         }
      }
      catch (Exception e) {
         System.out.println(e);
      }
   }
}

Output

ArrayList:
ARB-;-Trying to add an element in between iteration
java.util.ConcurrentModificationException

Approach 2

Use of the Iterator.next() Method

In this possible approach,we are going to apply the iterator.next() method. When a Java collection classes are fail, means a collection change its course while some threads traverse over the iterator.

HashSet<TableRecord> tableRecords = new HashSet<>();
...
for (Iterator<TableRecord> iterator = tableRecords.iterator();
iterator.hasNext(); ) {
   TableRecord record = iterator.next();
   if (record.getDependency() == null) {
      for (Iterator<TableRecord> dependencyIt = tableRecords.iterator();
      dependencyIt.hasNext(); ) {
         TableRecord dependency = dependencyIt.next();
         if (dependency.getDependency() != null &&
         dependency.getDependency().getId().equals(record.getId())) {
            tableRecords.remove(record);
         }
      }
   }
}

Example

//Java program to illustrate the java.util.ConcurrentModificationException method by using the iterator.next() function
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ConcurrentModificationExceptionARBRDDExample {
   public static void main(String args[]) {
      List<String> myList = new ArrayList<String>();
      myList.add("16");
      myList.add("07");
      myList.add("10");
      myList.add("2001");
      myList.add("1997");
      Iterator<String> it = myList.iterator();
      while (it.hasNext()) {
         String value = it.next();
         System.out.println("List Value Is Here. Have A Look @ARBRDD:- ->" + value);
         if (value.equals("2001"))
         myList.remove(value);
      }
      Map<String, String> myMap = new HashMap<String, String>();
      myMap.put("16", "16");
      myMap.put("07", "07");
      myMap.put("1997", "1997");
      Iterator<String> it1 = myMap.keySet().iterator();
      while (it1.hasNext()) {
         String key = it1.next();
         System.out.println("Map Value:" + myMap.get(key));
         if (key.equals("07")) {
            myMap.put("16", "2001");
         }
      }
   }
}

Output

List Value Is Here. Have A Look @ARBRDD:-->16
List Value Is Here. Have A Look @ARBRDD:-->07
List Value Is Here. Have A Look @ARBRDD:-->10
List Value Is Here. Have A Look @ARBRDD:-->2001
Map Value:1997
Map Value:16
Map Value:07

Conclusion

The ConcurrentModificationException can be encounterd when a particular object try to modify itself in a concurrent manner while we use an iterator class in a particular program. Today in this article we have learned about the modification of a concurrent method. By using the above mentioned syntax and algorithm, we have build some Java code to solve the problem statement in an efficient manner.

Updated on: 29-Dec-2023

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements