ConcurrentModificationException in Java with Examples
Feb 07, 2025 pm 12:01 PMIn Java multithreaded environment, if the method encounters concurrent modifications during resource detection, an exception may be thrown. At this time, the object is in a non-modified state. ConcurrentModificationException
ConcurrentModificationException
Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:000) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:000) at com.journaldev.ConcurrentModificationException.ConcurrentModificationExceptionExample.main(ConcurrentModificationExceptionExample.java:00)
Exception detection and iteration are not defined in the
method.- Use an internal flag named , the fast-failed iterator blocks in the loop.
-
modCount
Exception algorithmConcurrentModificationException
This algorithm demonstrates how to generate
java.util.ConcurrentModificationException
- Start the process.
- Declare and import the necessary Java packages.
- Declare a public class.
- Declare a string parameter.
- Create an ArrayList object.
- Create a new ArrayList.
- Fill in ArrayList.
- Declare a try block.
- Print list.
- Declare an iterator.
- Use while loop to traverse the next value.
- Add a value during the iteration.
- Print the updated ArrayList.
- Use while loop to traverse the next value.
- Catch exception.
- Print exception information.
- Get the value.
- Stop the process.
Exception syntaxConcurrentModificationException
The following syntax shows how to generate an
ConcurrentModificationException
// ... (代碼片段省略,與原文類似,但使用更簡(jiǎn)潔的變量名和注釋) ...exceptions in a Java environment.
ConcurrentModificationException
- Method 1: Modify during the iteration process
- This method directly modifys the collection during the iteration process. When the fast-fail iterator fails, an exception is thrown.
for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) { Integer integer = iterator.next(); if(integer == 2) { iterator.remove(); // 使用迭代器的remove()方法安全地移除元素 } }
- Method 2: Use the iterator
- and methods and loop
next()
remove()
This method uses the
iterator.next()
ConcurrentModificationException
Exceptions usually occur when the collection is modified concurrently. This article describes how to avoid this exception and provides corresponding Java code examples. This exception can be effectively avoided using thread-safe collection classes such as CopyOnWriteArrayList
or ConcurrentHashMap
, as well as the iterator's remove()
method.
The above is the detailed content of ConcurrentModificationException in Java with Examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

High-frequency questions in Java interviews are mainly focused on basic syntax, object-oriented, multithreaded, JVM and collection frameworks. The most common questions include: 1. There are 8 basic Java data types, such as byte, short, int, long, float, double, char and boolean. It is necessary to note that String is not the basic data type; 2. Final is used to modify classes, methods or variables to represent immutable, and finally is used to ensure code execution in exception processing. Finalize is an Object class method for cleaning before garbage collection; 3. Multi-thread synchronization can be achieved through synchronized keywords, ReentrantLock, and vo.

The method of using preprocessing statements to obtain database query results in PHP varies from extension. 1. When using mysqli, you can obtain the associative array through get_result() and fetch_assoc(), which is suitable for modern environments; 2. You can also use bind_result() to bind variables, which is suitable for situations where there are few fields and fixed structures, and it is good compatibility but there are many fields when there are many fields; 3. When using PDO, you can obtain the associative array through fetch (PDO::FETCH_ASSOC), or use fetchAll() to obtain all data at once, so the interface is unified and the error handling is clearer; in addition, you need to pay attention to parameter type matching, execution of execute(), timely release of resources and enable error reports.

Create and use SimpleDateFormat requires passing in format strings, such as newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); 2. Pay attention to case sensitivity and avoid misuse of mixed single-letter formats and YYYY and DD; 3. SimpleDateFormat is not thread-safe. In a multi-thread environment, you should create a new instance or use ThreadLocal every time; 4. When parsing a string using the parse method, you need to catch ParseException, and note that the result does not contain time zone information; 5. It is recommended to use DateTimeFormatter and Lo

In Go language, structtags is meta information attached to the structure field, which is used to control serialization, deserialization behavior or provide library configuration. 1.structtags are written in backticks in key:"value" format, such as json:"name", which determines the serialization method of the field; 2. Multiple tags can coexist, and each library parses the required parts, such as json and gorm together; 3. Mapstructure is used to configure mapping, and supports omitting tags and nested structures when the field names are consistent; 4. Pay attention to avoid spelling errors, fields need to be exported, and tags cannot be abused to affect readability. Mastering its usage will help improve development efficiency and generation

BiConsumer is a functional interface in Java that handles operations that do not return results. It belongs to the java.util.function package and is suitable for scenarios where two data are required to operate at the same time, such as key-value pairs that traverse Map. A common usage is to iterate with Map's forEach method. Unlike other functional interfaces such as Consumer and BiFunction, BiConsumer does not generate a return value. The implementation methods include lambda expressions, method references and anonymous classes. When using them, you need to pay attention to the order of type parameters, non-returnable values, and exception handling.
