How to Solve ConcurrentModificationException in Java?

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.
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 classesimport java.io.*;import java.util.*; // Main Classclass 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 packagesimport java.io.*;import java.util.*;import java.util.Iterator; // Main Classclass 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);    }}
List 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.
 
anikaseth98
clintra
sagar0719kumar
akshaysingh98088
anikakapoor
avtarkumar719
Java-Exceptions
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to download and install Python Latest Version on Android
How to Add External JAR File to an IntelliJ IDEA Project?
How to Fix “passwd: Authentication token manipulation error” in Linux
Spring Boot | How to publish JSON messages on Apache Kafka
How to install Python on Windows?
Arrays.sort() in Java with examples
For-each loop in Java
Arrays in Java
Multidimensional Arrays in Java
Split() String method in Java with examples