ConcurrentModificationException in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

In this article, we are going to learn about concurrent modification exceptions in Java. Before getting started with the topic, let's get an overview of what is an exception in Java, and also about the concurrent modification exception in Java.

Exceptions in Java: In java, many times some unwanted or unexpected event might occur in our code. That unexpected event is termed an exception in Java. Now, these exceptions occur during the run time of our code, and it disrupts the normal execution of the code. A few of the major reasons why exceptions occur in the code are Invalid user input, Device failure, and Loss of network connection. Java is a programming language, that provides different ways, by which we can handle the exceptions, the mechanism to handle the runtime exceptions are known as exception handling.

concurrent modification exception java : The concurrent modification exception occurs in Java if we try to modify any object concurrently, although we do not have permission to modify it. Usually, when we are working with Java Collection classes, this type of exception might occur.

So let us now begin with the main agenda of our article, concurrent modification exception java.

Introduction to ConcurrentModificationException in Java

Before learning about the ConcurrentModificationException in Java, let us understand what is an exception in Java.

Exceptions in Java: In java, many times some unwanted or unexpected event might occur in our code. That unexpected event is termed an exception in Java. Now, these exceptions occur during the run time of our code, and it disrupts the normal execution of the code. A few of the major reasons why exceptions occur in the code are Invalid user input, Device failure, and Loss of network connection. Java is a programming language, that provides different ways, by which we can handle the exceptions, the mechanism to handle the runtime exceptions are known as exception handling. There are different types of exceptions in Java, such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. ConcurrentModificationException is one of them. Let us discuss it.

ConcurrentModificationException : The concurrent modification exception occurs in Java if we try to modify any object concurrently, although we do not have permission to modify it. Usually, when we are working with Java Collection classes, this type of exception might occur.

For instance, we have a collection list in our code, and some thread is iterating over it, whereas some other thread is trying to modify its value, during the process of iteration, then in this type of scenario we might get this ConcurrentModificationException. This is because the iteration outcome becomes undefined with it. This type of exception is thrown by some implementation of the Iterator class, which also includes all those general-purpose implementations of the Iterator given by the JRE. We call those Iterators fail-fast Iterators, which instantly throw an exception whenever they run into a problem rather than having to deal with the collection's unpredictable behavior in the future.

Note : It is not necessary that when a Collection is tried to be modified by some other thread, this exception will be thrown. This exception might be thrown if a single thread has some methods called which are trying to disobey the contract of the object. This exception can be thrown, if the Collection object is tried to be modified by some thread, while the collection is being iterated by some fail-fast iterator, the iterator will throw the exception.

Declaration

Let us look at the declaration of ConcurrentModificationException in Java.

Syntax :

Explanation :

  • In the above syntax, we are declaring the Java ConcurrentModificationException.
  • The ConcurrentModificationException exception in Java belongs to the java.util package.

Constructor Summary of ConcurrentModificationException in Java

There are several constructors of the ConcurrentModificationException in Java, let us discuss them in detail.

ConstructorDescription
public ConcurrentModificationException()This type of constructor, creates a new ConcurrentModificationException in Java, with no parameters.
public ConcurrentModificationException(String message)This type of constructor, creates a new ConcurrentModificationException in Java, with a single parameter which will consist of a message in detail, that will specify the exception.
public ConcurrentModificationException(Throwable cause)This type of constructor, creates a new ConcurrentModificationException in Java, with a specific cause and a message in details of cause==null ? null : cause.toString() (which basically consists of a class and a detailed message of the cause.)
public ConcurrentModificationException(String message, Throwable cause)This type of constructor, creates a new ConcurrentModificationException in Java, with two parameters which will consist of a message in details, and also a cause. cause==null?null: cause.toString(). Later on, we can retrieve the message by Throwable.getMessage() and we can also retrieve the cause by Throwable.getCause() methods.

Method Summary of ConcurrentModificationException in Java

MethodDescription
cloneThe clone() method is inherited by the java.lang.Object class, and using this method we can creates an exact clone or of any other object.
equalsThe equals() method is inherited by the java.lang.Object class, and this method can be used to compare two objects and check whether both objects are equal or not.
finalizeThe finalize() method is inherited by the java.lang.Object class, and it used to clean up the memory before any object is destroyed. This method is called by the Garbage collector, before the object is destroyed by the memory.
getClassThe getClass() method is inherited by the java.lang.Object class. The run-time class of this object is returned by this getClass() method.
hashCodeThe hashCode() method is inherited by the java.lang.Object class. This method calculate the hash value of given input object.

ConcurrentModificationException in Java Examples

Let us now look at some examples of the ConcurrentModificationException in Java, for more clear understanding.

Example 1

Abstract :

In this example, we will see how the program will throw the ConcurrentModificationException in Java when we try to modify a List concurrently, although we do not have permission to modify it.

Code :

Output :

Explanation :

  • In the above code, firstly we are importing all the important classes like Iterator, ArrayList, and List required in this code, from the java.util package.
  • Inside the main method, we are creating an object new List Object of Integer type.
  • Then we add some value inside the list.
  • Inside the try block we are iterating the iterator and printing the value of the list, and while iterating with the next() method of the iterator, we are also removing an element from the list simultaneously. Hence, ConcurrentModificationException will raise here as an element is removed during the iteration.
  • Hence, it will go to the catch block, and print the exception.

Now, let us see what will happen, if we use a HashMap instead of an ArrayList.

Example 2

Abstract :

In this example, we will see whether the program will throw a ConcurrentModificationException in Java or not if we are using a HashMap in place of an ArrayList.

Code :

Output :

Explanation :

  • In the above code, firstly we are importing all the important classes required in this code, from the java.util package.
  • Inside the main method, we are creating a new object of HashMap. In which, the key is of type Integer, and the value is of type Character.
  • Then we add some keys and value pairs inside the HashMap.
  • Inside the try block we are iterating the iterator and printing the value of the HashMap, and while iterating with the next() method of the iterator, we are also modifying an element from the HashMap simultaneously.
  • We can observe, the program got executed successfully, and no ConcurrentModificationException will be thrown here as there are no changes in the size of the HashMap.
  • Hence, it will be executed successfully, and print all the values of the HashMap.
  • Here we are modifying the value of a key pair in the HashMap, that is why no ConcurrentModificationException is thrown. If we try to remove any key-value pair from the HashMap, then this will also throw a ConcurrentModificationException as the size of the map is manipulated in this case.

How to Resolve ConcurrentModificationException?

The ConcurrentModificationException exception in Java can be resolved by iterating over the elements of the ArrayList using the formal for loop instead of the modified for a loop. Since Iterator is not been used by the formal for loop to traverse over the elements of the Collection, It will not throw any ConcurrentModificationException.

Abstract :

In this example we will see how we can resolve the ConcurrentModificationException, using the for loop for traversing the Collection.

Code :

Output :

Explanation :

  • In the above code, firstly we are importing all the important classes like Iterator, ArrayList, List required in this code, from the java.util package.
  • Inside the main method, we are creating an object new List Object of Integer type.
  • Then we add some value inside the list.
  • Inside the try block we are traversing the List using for loop and printing the value of the list, and while traversing, we are also removing an element from the list simultaneously using the remove() method of the Collection. Hence, we can observe the program got executed successfully, and no ConcurrentModificationException will be thrown here, the reason is we are using the for loop here for traversing the elements of the List, and it will not cause any ConcurrentModificationException.

How to Avoid ConcurrentModificationException?

Sometimes While iterating a Collection, we might occasionally want to remove elements from a collection. In that case, if we want to avoid or resolve this ConcurrentModificationException There are some remedies if this is the situation.

Using an Iterator Directly

Iterator is been used by a for-each loop behind the scenes but is less verbose. However, if we had to refactor our earlier test to utilize an Iterator(), we can use some additional methods, such as remove(). Let us try using this remove() method to modify our list instead :

Abstract :

In this example we will see how we can resolve the ConcurrentModificationException, using the remove() method of the iterator.

Code :

Output :

Explanation :

  • In the above code, firstly we are importing all the important classes like Iterator, ArrayList, List required in this code, from the java.util package.
  • Inside the main method, we are creating an object new List Object of Integer type.
  • Then we add some value inside the list.
  • Inside the try block we are iterating the iterator and printing the value of the list, and while iterating with the next() method of the iterator, we are also removing an element from the list simultaneously using the remove() method of the Iterator. Hence, we can observe the program got executed successfully, and no ConcurrentModificationException will be thrown here, the reason is we are using the remove() method here, and it will not cause any ConcurrentModificationException. It is safe to call while iterating.

Not Removing During Iteration

If we still want to use the for-each loop, and remove any element from the Collection, while iterating it, we can do that. It's just that we need to remove the element after the iteration get's over. Let's try this out by adding what we want to remove to a remove list as we iterate:

Abstract :

In this example we will see how we can resolve the ConcurrentModificationException, by removing the element after the iteration get's over.

Code :

Output :

Explanation :

  • In the above code, firstly we are importing all the important classes like Iterator, ArrayList, List required in this code, from the java.util package.
  • Inside the main method, we are creating new objects of two different lists: list, and remove.
  • Then we add some value inside the list.
  • Inside the try block we are iterating the iterator and printing the value of the list, and while iterating with the next() method of the iterator, we are also storing the element from the list which we want to remove inside the remove list.
  • After the iteration gets over, we are removing all the elements inside the remove list, from the given list.
  • Hence, we can observe the program got executed successfully, and no ConcurrentModificationException will be thrown here.

How to Avoid ConcurrentModificationException in Multithreaded Environments?

We can follow these precautions to avoid the ConcurrentModificationException in multithreaded environments. Let us discuss them in detail.

  • To avoid the ConcurrentModificationException in multithreaded environments, we can prefer iterating over an array rather than a collection. However, using an array is only preferred if the size of the array is small, and will degrade in performance for larger ones.
  • We can also avoid the ConcurrentModificationException in multithreaded environments by placing the collection in a synchronized block, by this the collection will get locked. However, this may not be the most optimal approach as the main purpose of multi-threading is not fulfilled by this method.
  • We can also avoid the ConcurrentModificationException in multithreaded environments by using the concurrent collections of Java, such as the ConcurrentHashMap and CopyOnWriteArrayList classes, which can avoid the ConcurrentModificationException to occur.

How to Avoid ConcurrentModificationException in a single-threaded environment?

To Avoid ConcurrentModificationException in a single-threaded environment, we can use the remove() function of the iterator to remove any element from the List, while iterating it. But by using the remove() method, we can remove the same object and not any other object from the list. For more clear understanding, Let us see a code example of how we can use the remove() method to avoid the exception.

Code :

Output :

Explanation:

  • In the above code, firstly we are importing all the important classes like Iterator, ArrayList, List required in this code, from the java.util package.
  • Inside the main method, we are creating an object new List Object of Integer type.
  • Then we add some value inside the list.
  • Inside the try block we are iterating the iterator and printing the value of the list, and while iterating with the next() method of the iterator, we are also removing an element from the list simultaneously using the remove() method of the Iterator. Hence, we can observe the program got executed successfully, and no ConcurrentModificationException will be thrown here, the reason is we are using the remove() method here, and it will not cause any ConcurrentModificationException. It is safe to call while iterating.

Conclusion

In this article, we learned about the concurrent modification exception Java. Let us recap the points we discussed throughout the article:

  • In java, some unwanted or unexpected event might occur in our code. That unexpected event is termed an exception in Java.
  • The concurrent modification exception occurs in Java if we try to modify any object concurrently, although we do not have permission to modify it. Usually, when we are working with Java Collection classes, this type of exception might occur.
  • Different constructors of ConcurrentModificationException in Java are public ConcurrentModificationException(), public ConcurrentModificationException(String message), public ConcurrentModificationException(Throwable cause), public ConcurrentModificationException(String message, Throwable cause).
  • Then we have seen different examples of ConcurrentModificationException in Java.
  • We have also learned how to resolve and avoid the ConcurrentModificationException in Java.