×

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes.

When another thread is iterating over a Collection, no thread may edit that Collection. This is because with each iteration, the outcome gets more uncertain. This error is thrown by some Iterator class implementations, including all of the general-purpose Iterator implementations offered by the JRE. These iterators are known as fail-fast because they instantly throw an exception if they run into a problem rather than having to deal with the collection's unpredictable behaviour in the future.

This exception need not be raised every time another thread tries to make changes to a Collection object. It may also occur if a single thread calls several methods that attempt to break the object's contract. This could occur if a thread tries to edit a collection object while the collection is being iterated by a fail-fast iterator, in which case the iterator will throw an exception.

Concurrentmodificationexception.java

import java.awt.List;  
import java.util.*;  
  
public class Concurrentmodificationexception {  
  
    public static void main(String[] args) {  
        ArrayList list = new ArrayList<>();  
  
        list.add(9);  
        list.add(5);  
        list.add(10);  
        list.add(6);  
        list.add(3);  
  
        Iterator it = list.iterator();  
        while (it.hasNext()) {                   
Integer value = it.next();              
            System.out.println("List Value:" + value);  
            if (value.equals(10))  
                list.remove(value);  
        }  
  
    }  
  
}  

Output:

Explanation:

According to this message, the exception is thrown when the next method is called because the list is being iterated by the iterator while we are simultaneously making changes to it. However, if we apply the changes shown below to the hashmap, it won't raise an exception since the hashmap's size won't change.

Concurrentmodificationexception.java

import java.awt.List;  
import java.util.*;  
  
public class Concurrentmodificationexception {  
  
    public static void main(String[] args) {  
          
        HashMap map = new HashMap<>();  
        map.put(1, 6);  
        map.put(2, 4);  
        map.put(3,9);  
          
        Iterator it = map.keySet().iterator();  
        while(it.hasNext()) {  
            Integer key = it.next();  
            System.out.println("Value of the Map:" + map.get(key));  
            if (key.equals(2)) {  
                map.put(3, 4);  
            }  
        }     
    }  
}

Output:

Explanation:

This example is perfect since the size of the map stays constant as the iterator iterates over it. In the if statement, just the map is being updated.

Constructors of ConcurrentModificationException

There are 4 different types of ConcurrentModificationException constructors. –

  1. public ConcurrentModificationException(): This generates a ConcurrentModificationException with no parameters.
  2. public ConcurrentModificationException(String message): ConcurrentModificationExceptions are produced as a result, each with a descriptive message describing the exception.
  3. public ConcurrentModificationException(Throwable cause): This generates a ConcurrentModificationException with the message (cause==null?null:cause.toString()) and the cause (cause==null?null). The Throwable later determines the cause. getCause().
  4. public ConcurrentModificationException(String message, Throwable cause): A ConcurrentModificationException is produced as a result, complete with a cause and descriptive message. (cause==null?null:cause.toString()). Throwable later gets the message back. Throwable will eventually obtain the results of getMessage() and cause. getCause().

How can ConcurrentModificationException be prevented in a multi-threaded environment?

In a multi-threaded system, the ConcurrentModificationException can be avoided by doing the following:

  1. We may iterate over the array rather than the collection class. In this method, we can work extremely efficiently with small lists, but if the array size is too huge, the performance will suffer.
  2. The list might also be locked by including it in the synchronised block. This strategy is useless since it defeats the primary goal of employing multi-threading.
  3. Classes for ConcurrentHashMap and CopyOnWriteArrayList will be included in JDK 1.5 or above. We can prevent concurrent modification exceptions with the use of these classes.

How can ConcurrentModificationException be prevented in a context with only single thread?

You may remove an item from an underlying collection object by using the remove() method of an iterator.

To remove an element from an underlying collection object, use the iterator's remove() function. However, in this instance, just that specific object may be deleted from the list. Let's use Concurrent Collection classes to execute an example.

ConcurrentModificationException.java

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class ConcurrentModificationException {


public static void main(String[] args) {


List myList = new CopyOnWriteArrayList();


myList.add("2");
myList.add("4");
myList.add("6");
myList.add("8");
myList.add("10");


Iterator it = myList.iterator();
while (it.hasNext()) {
String value = it.next();
System.out.println("List Value:" + value);
if (value.equals("8")) {
myList.remove("4");
myList.add("6");
myList.add("7");
}
}
System.out.println("List Size:" + myList.size());
Map myMap = new ConcurrentHashMap();
myMap.put("1", "1");
myMap.put("2", "2");
myMap.put("3", "3");
Iterator it1 = myMap.keySet().iterator();
while (it1.hasNext()) {
String key = it1.next();
System.out.println("Map Value:" + myMap.get(key));
if (key.equals("1")) {
myMap.remove("3");
myMap.put("4", "4");
myMap.put("5", "5");
}
}
System.out.println("Map Size:" + myMap.size());
}
}

Output:

← Prev Next →


Related Topics

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.