ConcurrentModificationException in Java with Examples


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 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 illustrate the ConcurrentModificationException by using as an element is added during the iteration process and performing modification

  • Approach 2 − Java program to illustrate the java.util.ConcurrentModificationException method by using the iterator.next(), remove() function as well as deploy a loop

Approach 1: use Iteration Process and Perform the Modification Process

Use of the Addition on Element 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 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

Use of the Iterator Modification Method

In this possible approach, we are going to apply the modification process 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 show ConcurrentModificationException when exception is raised as a modification is done after the iteration
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 Is Here: ");
         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: "
         + arr.add("Going Soon"));
         System.out.println(
         "\nUpdated ArrayList Is Here: ");
         iter = arr.iterator();
         while (iter.hasNext()) {
            System.out.print(iter.next()
            + "-;-");
         }
      }
      catch (Exception e) {
         System.out.println(e);
      }
   }
}

Output

ArrayList Is Here:
ARB_;_BANGLADESH_;_RDD_;_INDIA_;_Trying to add an element in between iteration:
true
Updated ArrayList Is Here:
ARB-;-BANGLADESH-;-RDD-;-INDIA-;-Going Soon-;-

Approach 2: Using the Iterator.next(), Remove() Function as well as Deploy a Loop

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.

@Test(expected = ConcurrentModificationException.class)
public void whilstRemovingDuringIteration_shouldThrowException() throws
InterruptedException {
	List<Integer> integers = newArrayList(1, 2, 3);
	for (Integer integer : integers) {
		integers.remove(1);
	}
}
List<Integer> integers = newArrayList(1, 2, 3);
List<Integer> toRemove = newArrayList();
for (Integer integer : integers) {
	if(integer == 2) {
		toRemove.add(integer);
	}
}
integers.removeAll(toRemove);
assertThat(integers).containsExactly(1, 3);

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

Use of the Loop on an Array

In this possible approach,we are going to apply a single thread and will add some extra objects into it. The ConcurrentModificationException can be achived, when we try to modify the whole structure with a particular sub list.

Example

//Java program to illustrate and deploy a loop to avoid java.util.ConcurrentModificationException in an array list
import java.util.ArrayList;
import java.util.List;
public class ConcurrentModificationExceptionWithArrayListSubList {
   public static void main(String[] args) {
      List<String> names = new ArrayList<>();
      names.add("Kollam");
      names.add("Dhaka");
      names.add("Chennai");
      names.add("Palani");
      List<String> first2Names = names.subList(0, 2);
      System.out.println(names + " , " + first2Names);
      names.set(1, "Kolkata");
      System.out.println(names + " , " + first2Names);
      names.add("Kochi");
      System.out.println(names + " , " + first2Names);
   }
}

Output

[Kollam, Dhaka, Chennai, Palani] , [Kollam, Dhaka]
[Kollam, Kolkata, Chennai, Palani] , [Kollam, Kolkata]
Exception in thread "main" java.util.ConcurrentModificationException
at
java.base/java.util.ArrayList$SubList.checkForComodification(ArrayList.java:141
5)
at java.base/java.util.ArrayList$SubList.listIterator(ArrayList.java:1284)
at java.base/java.util.AbstractList.listIterator(AbstractList.java:313)
at java.base/java.util.ArrayList$SubList.iterator(ArrayList.java:1280)
at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:451)
at java.base/java.lang.String.valueOf(String.java:4225)
at
ConcurrentModificationExceptionWithArrayListSubList.main(ConcurrentModification
ExceptionWithArrayListSubList.java:16)

Use of the Remove() Iterator Method

In this possible approach,we are going to apply the remove() method. By using this we will remove the same objects from a list but not any object.

Example

//Java program to avoid the ConcurrentModificationException in single-threaded environment by using the iterator to remove() a function
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class AvoidConcurrentModificationException{
   public static void main(String[] args){
      List<String> myList = new CopyOnWriteArrayList<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:" + value);
         if (value.equals("3")) {
            myList.remove("4");
            myList.add("6");
            myList.add("7");
         }
      }
      System.out.println("List Size Is Now :" + myList.size());
      Map<String, String> myMap = new ConcurrentHashMap<String,
      String>();
      myMap.put("16", "07");
      myMap.put("2", "16");
      myMap.put("2022", "13110");
      Iterator<String> it1 = myMap.keySet().iterator();
      while (it1.hasNext()) {
         String key = it1.next();
         System.out.println("Map Value Is Here:" + myMap.get(key));
         if (key.equals("1")) {
            myMap.remove("3");
            myMap.put("4", "4");
            myMap.put("5", "5");
         }
      }
      System.out.println("Map Size Is Here. Have A Look:" +
      myMap.size());
   }
}

Output

List Value:16
List Value:07
List Value:10
List Value:2001
List Value:1997
List Size Is Now :5
Map Value Is Here:16
Map Value Is Here:07
Map Value Is Here:13110
Map Size Is Here. Have A Look:3

Conclusion

The ConcurrentModificationException can be encounterd when a particular object try to modify itself in a concurrent manner. 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

37 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements