How to Solve ConcurrentModificationException in Java?
Last Updated :
02 Mar, 2022
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 file is not available then we will get RuntimeException saying FileNotFoundException. If FileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.
There are mainly two types of exception in java as follows:
- Checked Exceptions are the exceptions that are checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error.
- Unchecked Exceptions are the exceptions that are not checked by the compiler, whether programmer handling or not such types of exceptions are called unchecked exceptions. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc.
Note: Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.
Implementation:
ConcurrentModificationException is the child class of RuntimeException and hence it is an unchecked exception. This exception rises when an object is tried to be modified concurrently when it is not permissible i.e when one thread is iterating over some collection class object and if some other thread tried to modify or try to make some changes on that collection object then we will get ConcurrentModificationException. This exception usually occurs when we are working with Java collections classes.
Example
Java
// Java program to illustrate
// ConcurrentModificationException
// Importing all classes from java.util package
// Importing input output classes
import java.io.*;
import java.util.*;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of ArrayList
// Declaring object of Integer type
ArrayList<Integer> list = new ArrayList<>();
// Adding element to ArrayList object created above
// using the add() method
// Custom input elements
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
// Display all the elements of ArrayList object
System.out.println("List Value Before Iteration:"
+ list);
// Creating an iterator object to
// iterate over the ArrayList
Iterator<Integer> it = list.iterator();
// Condition check
// It holds true till there is single element
// remaining in the List
while (it.hasNext()) {
Integer value = it.next();
// Here we are trying to remove the one entry of
// ArrayList base on the if condition and hence
// We will get Concurrent ModificationException
if (value.equals(3))
list.remove(value);
}
// Print and display the value of ArrayList object
System.out.println("List Value After Iteration:"
+ list);
}
}
Output:
Output explanation:
The above program is a single-threaded program and here we can avoid ConcurrentModificationException by using iterator's remove( ) function, we can remove an object from an underlying collection object without getting any exception.
Example 2
Java
// Java Program to illustrate
// ConcurrentModificationException
// Importing the required packages
import java.io.*;
import java.util.*;
import java.util.Iterator;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an collection class object
// Declaring object of integer type
ArrayList<Integer> list = new ArrayList<>();
// Adding element to ArrayList
// using add() method
// Custom integer input entries
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
// Display the value of ArrayList
System.out.println("List Value Before Iteration:"
+ list);
// Creating an iterator object
// to iterate over the ArrayList
Iterator<Integer> itr = list.iterator();
// Condition check
// it holds true till there is single element
// remaining in the List
while (itr.hasNext()) {
// next() method() looks out for next element in
// the List
Integer value = itr.next();
// Here we are trying to remove the one entry of
// ArrayList base on the given if condition and
// hence
// We will get Concurrent ModificationException
if (value.equals(3))
itr.remove();
}
// Display the value of ArrayList
System.out.println("List Value After iteration:"
+ list);
}
}
OutputList Value Before Iteration:[1, 2, 3, 4, 5]
List Value After iteration:[1, 2, 4, 5]
Note: In multi-threaded program we can avoid ConcurrentModificaionException by using ConcurrentHashMap and CopyOnWriteArrayList classes. These classes help us in avoiding ConcurrentModificaionException.
Similar Reads
How to Avoid ConcurrentModificationException in Java? 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 requi
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
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
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
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
ConcurrentSkipListSet remove() method in Java The java.util.concurrent.ConcurrentSkipListSet.remove() method is an in-built function in Java which is used to remove an element if it is present in this set. Syntax: ConcurrentSkipListSet.remove(Object o) Parameters: The function accepts a single parameter o i.e. the object to be removed. Return V
2 min read