Home > Java > javaTutorial > body text

Java ConcurrentModificationException

PHPz
Release: 2024-08-30 16:13:30
Original
553 people have browsed it

Java Programming Language provides a range of exception handling cases, and Concurrent Modification Exception is one of them. Concurrent Modification Exception occurs when a thread in a program is trying to modify an object, which does not have permissions to be edited while in the current process. So simply, when we attempt to edit an object which is being currently used by another process, the ConcurrentModificationException will appear.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

A very plain example would be a collection that has been under process by a thread. The collection under process is not allowed to be modified and hence throws ConcurrentModificationException.

Syntax:

Below is the simplest syntax for the exception. ConcurrentModificationException is part of the java lang RunTimeException, and it extends it.

public class Concurrent Modification Exception
extends Runtime Exception
Copy after login

How ConcurrentModificationException Works in Java?

It is understandable that we set some limits and permissions according to our needs when we create objects in Java. But sometimes, we attempt to change the values or amend the list, just when it is in the thread, and that’s when ConcurrentModificationException appears because the object has been used by another thread and cannot be edited or amended.

It is also important to know that this exception does not always mean that there’s an object being modified concurrently. In the case of a single thread, this exception can be thrown if method invocations are happening, which in some way violates the object contract.

Constructors:

A very basic constructor for ConcurrentModificationException is as simple as follows: ConcurrentModificationException (). Other than the simple constructor, we have the following contributors which can be used as per need:

  • ConcurrentModificationException ( String textmessage): Constructor with a simple message.
  • ConcurrentModificationException ( String textmessage, Throwable textcause): Constructor with a message and detailed cause.
  • ConcurrentModificationException ( Throwable textcause): Constructor with a cause, here the cause can be null, which means it’s unknown.

Examples of Java ConcurrentModificationException

Now that we have understood what the Concurrent Modification Exception is and how it works let’s move to implementation. We will now understand the exception with an example; for example, we will have an Array List, and along with some operation, we will attempt to modify it, which will result in an exception. Code for the example is as follows:

Example #1

Code:

import java.awt.List;
import java.util.*;
public class ConcurrentModificationException {
public static void main ( String[] args) {
ArrayList<Integer> Numberlist = new ArrayList<Integer> () ;
Numberlist.add ( 1) ;
Numberlist.add ( 2) ;
Numberlist.add ( 3) ;
Numberlist.add ( 4) ;
Numberlist.add ( 5) ;
Iterator<Integer> it = Numberlist.iterator () ;
while ( it.hasNext () ) {
Integer numbervalue = it.next () ;
System.out.println ( "List Value:" + numbervalue) ;
if ( numbervalue .equals ( 3) )
Numberlist.remove ( numbervalue) ;
}
}
}
Copy after login

Code Explanation: Started with few import files, then class deceleration and the main method. Initialized the array list and add a function to keep adding a number; this way, it’ll be under process. Upon every next addition, we are printing the List Value. But then we have an if loop, which will look for a number that equals 3, and once 3 is found, it will attempt to remove the number, and this is where the exception will encounter, and the program will be terminated. There won’t be any further additions to the list.

If you execute the above code without any error, the code will stumble upon an exception. That exception is at ConcurrentModificationException.main ( ConcurrentModificationException.java:14). The reason for this exception is clear that we attempted to modify a list, Numberlist. Refer to the below attached screenshot for proper output:

Java ConcurrentModificationException

As you can see, the program was executed as we intended, the print statements executed successfully until they met up with the value of 3. The program flow was interrupted at the value of 3 because we had an if loop, which looks for a value that equals three and deletes it. But the iterator is already in progress, and the attempt to delete the 3 will fail, and this throws the exception ConcurrentModificationException.

Example #2

for the purpose of the second example, we will attempt to execute a program that will successfully dodge the Concurrent Modification Exception. In the same code, if we try to modify the array list while in process, it will catch the ConcurrentModificationException, and the program will be terminated. Code for the second example is as follows:

Code:

import java.util.Iterator;
import java.util.ArrayList;
public class ConcurrentModificationException {
public static void main ( String args[])
{
ArrayList<String> arraylist = new ArrayList<String> ( ) ;
arraylist.add ( "One") ;
arraylist.add ( "Two") ;
arraylist.add ( "Three") ;
arraylist.add ( "Four") ;
try {
System.out.println ( "ArrayList: ") ;
Iterator<String> iteratornew = arraylist.iterator () ;
while ( iteratornew.hasNext ( ) ) {
System.out.print ( iteratornew.next ()
+ ", ");
}
System.out.println ( "\n\n Trying to add an element in between iteration:"
+ arraylist.add ( "Five") ) ;
System.out.println ( "\n Updated ArrayList: \n") ;
iteratornew = arraylist.iterator () ;
while ( iteratornew.hasNext ( ) ) {
System.out.print ( iteratornew.next ()
+ ", ");
}
}
catch ( Exception e) {
System.out.println ( e) ;
}
}
}
Copy after login

Code Explanation: Similar to the earlier program, we have the required files and methods. We are simply adding a few elements to the array list, and it is iterating; we add another element, which is Five. We will print the updated list upon the latest additions, which will have our newly added element. We have implemented the try-catch block to catch the exception. If any exception occurs, it will print the exception.

Output:

Java ConcurrentModificationException

As you can see in the output, the first array list is plain, with few elements. Then in the next line, we attempt to add an element while in iteration, the element is “Five”. It is successfully added, and it prints true for the sentence. And in the next line, we print an updated list, which has the Five-element. We have updated the list after the process is ending; if we try to add the element while in the process, it will throw the ConcurrentModificationException, and the program will cease.

How to Avoid ConcurrentModificationException in Java?

Avoiding Concurrent Modification Exception is possible on a different level of threads. To avoid a Concurrent Exception with a single thread environment, you can remove the object from the iterator and modify it, use remove ().

And in the case of a multi-thread environment, you have few choices like converting the list in the process into an array and then working on the array. Then you can also put a synchronized block over a list and lock it. But locking the list is not recommended as it may limit the advantages of multi-threading programming. Using a sublist to modify a list will result in nothing. Out of all the ways to avoid, the most preferred way is to wait until the execution is finished and then edit or modify the list or the object.

Conclusion

When a process is using one resource and another process attempts to edit or amend it, the exception ConcurrentModificationException will be thrown. The simplest method to avoid is to modify the list after iteration. Many methods are listed to avoid the exception but advised to implement them with small programs.

The above is the detailed content of Java ConcurrentModificationException. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template