×

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

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.