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:
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:
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!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
