Skip to content
Related Articles

Related Articles

Improve Article
How to Solve ConcurrentModificationException in Java?
  • Last Updated : 09 Jun, 2021

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:

  1. 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.
  2. 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 is rise 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 ArraList 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 elments 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 conditon 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 ArraList
        // usig 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() loos 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 conditon 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);
    }
}
Output
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.

 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :