Table of Contents
How ConcurrentModificationException Works in Java?
Examples of Java ConcurrentModificationException
Example #2
How to Avoid ConcurrentModificationException in Java?
Conclusion
Home Java javaTutorial Java 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
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!

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles