In multithreaded Java environments, attempting to modify a collection while iterating over it using an iterator can lead to a ConcurrentModificationException
. This exception arises because the collection's internal state becomes inconsistent.
Here's an example illustrating the exception:
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)
This exception occurs under these conditions:
- Modification during iteration: The iterator is not designed for concurrent modification.
- Fail-fast iterators: The iterator uses an internal flag (
modCount
) to detect modifications and throws the exception.
Algorithm for Reproducing the Exception
This algorithm demonstrates how to trigger a ConcurrentModificationException
in Java:
- Initialization: Create an
ArrayList
. - Population: Add elements to the
ArrayList
. - Iteration: Obtain an iterator using
list.iterator()
. - Modification: Inside the iteration loop, modify the
ArrayList
(e.g., add or remove elements). - Exception: The
ConcurrentModificationException
is thrown when the iterator detects the modification.
Code Example: Triggering the Exception
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ConcurrentModificationExample { public static void main(String[] args) { List<Integer> myList = new ArrayList<>(); myList.add(1); myList.add(2); myList.add(3); Iterator<Integer> iterator = myList.iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); System.out.println("Value: " + value); if (value == 2) { myList.remove(value); // Modification during iteration! } } } }
This code will throw a ConcurrentModificationException
because myList.remove(value)
modifies the list while the iterator is traversing it.
Safe Modification Techniques
To avoid this exception, use these approaches:
-
Iterator.remove()
: Use theiterator.remove()
method to remove elements during iteration. This method is safe because it's designed to work with the iterator's internal state. -
Copy the List: Create a copy of the list before iterating and modify the copy.
-
Use Concurrent Collections: For concurrent modification scenarios, use thread-safe collections like
CopyOnWriteArrayList
orConcurrentHashMap
. -
Synchronized Block: Enclose the iteration and modification within a synchronized block to ensure thread safety.
Example: Safe Removal using Iterator.remove()
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class SafeRemovalExample { public static void main(String[] args) { List<Integer> myList = new ArrayList<>(); myList.add(1); myList.add(2); myList.add(3); Iterator<Integer> iterator = myList.iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); System.out.println("Value: " + value); if (value == 2) { iterator.remove(); // Safe removal using iterator.remove() } } System.out.println(myList); } }
This revised code safely removes the element without throwing the exception. Remember to choose the appropriate technique based on your specific needs and concurrency requirements. Using concurrent collections is generally preferred for multithreaded scenarios.
The above is the detailed content of ConcurrentModificationException while using Iterator in Java. 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

Semaphore is used to control the number of concurrent accesses, suitable for resource pool management and flow-limiting scenarios, and control permissions through acquire and release; CountDownLatch is used to wait for multiple thread operations to complete, suitable for the main thread to coordinate child thread tasks. 1. Semaphore initializes the specified number of licenses, supports fair and non-fair modes, and when used, the release should be placed in the finally block to avoid deadlock; 2. CountDownLatch initializes the count, call countDown to reduce the count, await blocks until the count returns to zero, and cannot be reset; 3. Select according to the requirements: use Semaphore to limit concurrency, wait for all completions to use CountDown

The yield keyword is used to create generators, generate values on demand, and save memory. 1. Replace return to generate finite sequences, such as Fibonacci sequences; 2. Implement infinite sequences, such as natural sequences; 3. Process big data or file readings, and process them line by line to avoid memory overflow; 4. Note that the generator can only traverse once, and can be called by next() or for loop.

Preventing server-side template injection (SSTI) requires four aspects: 1. Use security configurations, such as disabling method calls and restricting class loading; 2. Avoid user input as template content, only variable replacement and strictly verify input; 3. Adopt sandbox environments, such as Pebble, Mustache or isolating rendering context; 4. Regularly update the dependent version and review the code logic to ensure that the template engine is configured reasonably and prevent the system from being attacked due to user-controllable templates.

The core goal of Java Security Manager configuration is to control code permissions, prevent overprivileged operations, and ensure normal function operation. The specific steps are as follows: 1. Modify the security.manager settings in the java.security file and use -Djava.security.policy to enable the security manager; 2. When writing the policy file, you should clarify the CodeBase and SignedBy properties, and accurately set the permissions such as FilePermission, SocketPermission, etc. to avoid security risks; 3. Common problems: If the class loading fails, you need to add defineClass permission, and the reflection is restricted, you need to reflect.

VariableVariables is a feature in PHP that uses variable values as another variable name. It uses $$var to achieve dynamic access to variables, process form input, and build flexible configuration structures. For example, $name="age"; echo$$name is equivalent to the output value of $age; common usage scenarios include: 1. Dynamic access to variables, such as ${$type.'_info'}, different variables can be selected according to the conditions; 2. Automatically assign values when processing form input, but attention should be paid to security risks; 3. Build a flexible configuration structure and obtain corresponding values through string names; when using it, you need to pay attention to code maintenance, naming conflicts and debugging difficulties. It is recommended that only

The basic PHP syntax includes: 1. Use wrapping code; 2. Use echo or print to output content, where echo supports multiple parameters; 3. Variables do not need to declare types, start with $. Common types include strings, integers, floating-point numbers, booleans, arrays and objects. Mastering these key points can help you get started with PHP development quickly.

PHP has 8 variable types, commonly used include Integer, Float, String, Boolean, Array, Object, NULL and Resource. To view variable types, use the gettype() or is_type() series functions. PHP will automatically convert types, but it is recommended to use === to strictly compare the key logic. Manual conversion can be used for syntax such as (int), (string), etc., but be careful that information may be lost.

PHP files are server-side scripting language files used for dynamic web development. They can process form data, connect to databases, generate dynamic content, and control access rights. It ends with .php, and the code returns the result to the browser after it is executed on the server. To run PHP files, you need to install a local server environment such as XAMPP, put the files in the server directory and access them through the browser. PHP is usually mixed with HTML. It is recommended to master HTML, CSS, JavaScript and basic programming concepts before learning. Practice more to get started quickly.
