search
HomeJavajavaTutorialJava ConcurrentModificationException

Java ConcurrentModificationException

Aug 30, 2024 pm 04:13 PM
java

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

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) ;
}
}
}</integer></integer></integer>

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) ;
}
}
}</string></string></string>

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!

Statement
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)