How to Avoid ConcurrentModificationException in Java?
Last Updated :
16 Jun, 2021
ConcurrentModificationException is a predefined Exception in Java, which occurs while we are using Java Collections, i.e whenever we try to modify an object concurrently without permission ConcurrentModificationException occurs which is present in java.util package.
Procedure: Some steps are required in order to avoid the occurrence of this exception in a single-threaded environment. They are as follows:
- Instead of iterating through collections classes, we can iterate through the arrays. This works perfectly fine for smaller lists what about the bigger list? It's very basic we know that if the array size is huge then it affects the performance. Hence, this method is only effective for smaller size arrays.
- The next method is the Synchronized block method, Here we actually lock the list in a synchronized block to avoid the exception. Isn't that cool? but guess what this is also not an effective method to avoid Exception Why? Because the purpose of multithreading is not being used.
- The better way is we have ConcurrentHashMap and CopyOnWriteArrayList Which is the best among the above Methods.
Methods:
Here two ways are proposed of which starting with the naive one and ending up with the optimal approach to reach the goal.
- Using Loops: We used the Iterator remove() method instead of that we can use a for loop to avoid ConcurrentModificationException in a Single-threaded environment. If we add any extra objects then we can ensure that our code takes care of them.
- Using the remove() Method: We can use the remove method to remove the object from the collection. Here there is a problem that is you can only remove the same object and not any other from the list
Example 1:
Java
// Java Program to Avoid
// AvoidConcurrentModificationException
// Importing Map and List utility classes
// from java.util package
import java.util.List;
import java.util.Map;
// Importing classes from java.util.concurrent package
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of List class
// Declaring object of string type
List<String> marvel
= new CopyOnWriteArrayList<String>();
// Adding elements to the above object created
// Custom input entries
marvel.add("IronMan");
marvel.add("BlackWidow");
marvel.add("Hulk");
marvel.add("DoctorStrange");
marvel.add("SpiderMan");
// Iterating over object created using size() method
for (int i = 0; i < marvel.size(); i++) {
// Print and display the object elements
// using get() method
System.out.println("Avenger : "
+ marvel.get(i));
// Condition check over object elements
// If specific element is matched
if (marvel.get(i).equals("BlackWidow")) {
marvel.remove(i);
i--;
// Add this specific element
marvel.add("CaptianAmerica");
}
}
// Now getting the final total size by checking
// how many elements are there inside object
System.out.println("Total Avengers : "
+ marvel.size());
}
}
OutputAvenger : IronMan
Avenger : BlackWidow
Avenger : Hulk
Avenger : DoctorStrange
Avenger : SpiderMan
Avenger : CaptianAmerica
Total Avengers :5
Note: The Exception can also occur if we try to modify the structure of original list with sublist. An example for the same is below,
Example 2:
Java
// Java Program to Illustrate ConcurrentModificationException
// WithArrayListSubList
// Importing List and Arraylist classes utility classes
// from java.util package
import java.util.ArrayList;
import java.util.List;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args) {
// Creating a List class object
// Declaring object of string type
List <String> names = new ArrayList <>();
// Adding elements to the object of List class
// Custom input entries
names.add("Java");
names.add("C++");
names.add("Phython");
names.add("JavaScript");
List < String > first2Names = names.subList(0, 2);
System.out.println(names + " , " + first2Names);
names.set(1, "Ruby");
// check the output below. :)
System.out.println(names + " , " + first2Names);
// Now we add another string to
// get ConcurrentModificationException
names.add("SQL");
// This line throws an exception
System.out.println(names + " , " + first2Names);
}
}
Output:
Henceforth, we have discussed how to avoid the Exception in both single-threaded and multithreaded environments successfully as depicted from the above outputs.
Similar Reads
How to Solve ConcurrentModificationException in Java? An unaccepted, unwanted event that disturbed the normal flow of a program is called an Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote fil
4 min read
ConcurrentModificationException in Java with Examples ConcurrentModificationException in Multi threaded environment In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown. If this e
3 min read
ConcurrentLinkedDeque add() method in Java The java.util.concurrent.ConcurrentLinkedDeque.add() is an in-built function in Java which inserts the specified element at the end of the deque. Syntax: conn_linked_deque.add(elem) Parameter: The method accepts only a single parameter elem which is to be added to tail of the ConcurentLinkedDeque. R
2 min read
ConcurrentLinkedQueue add() method in Java The add() method of ConcurrentLinkedQueue is used to insert the element, passed as parameter to add() of ConcurrentLinkedQueue, at the tail of this ConcurrentLinkedQueue. This method returns True if insertion is successful. ConcurrentLinkedQueue is unbounded, so this method will never throw IllegalS
2 min read
How to Use Counting Semaphore in Concurrent Java Application? Java Counting Semaphore maintains a specified number of passes or permissions, and the Current Thread must obtain a permit to access a shared resource. If a permit is already exhausted by threads other than that, it may wait until the permit becomes available as a result of the release of permits fr
3 min read