Home  >  Article  >  Java  >  How to solve Java concurrent modification exception (ConcurrentModificationException)

How to solve Java concurrent modification exception (ConcurrentModificationException)

WBOY
WBOYOriginal
2023-08-19 10:25:441799browse

How to solve Java concurrent modification exception (ConcurrentModificationException)

How to solve Java concurrent modification exception (ConcurrentModificationException)

In Java programming, when multiple threads modify a collection class object at the same time, it is easy to cause " ConcurrentModificationException" exception. This article describes the cause of the exception and provides various solutions and code examples.

1. Reason for exception

1.1 Collection class structure
ConcurrentModificationException exception usually occurs in iterator-based collection classes, such as ArrayList, HashMap, etc. They use a modCount variable internally to record the number of times the collection has been modified.

1.2 Concurrent modification
When one thread is performing an iterative operation, another thread adds, deletes or modifies the collection, thereby modifying the value of modCount, causing the iterator to think that the collection has been modified, and then throw A ConcurrentModificationException exception occurred.

2. Solution

2.1 Use the remove method of iterator
The iterator in the Java collection class provides the remove method, which can safely delete the current iteration from the collection element.

List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();

while (iterator.hasNext()) {
    String element = iterator.next();
    if (condition) {
        iterator.remove();
    }
}

2.2 Using concurrent collection classes
The Java concurrency package (java.util.concurrent) provides a series of thread-safe collection classes, which all use different concurrency mechanisms to solve the problem of concurrent modification.
For example, use ConcurrentHashMap instead of HashMap:

import java.util.concurrent.ConcurrentHashMap;

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

for (Map.Entry<String, String> entry : map.entrySet()) {
    if (condition) {
        map.remove(entry.getKey());
    }
}

2.3 Use synchronization mechanism
Use the synchronized keyword to synchronize the collection to ensure that only one thread can access the collection at the same time, thereby avoiding concurrent modification exceptions.

List<String> list = new ArrayList<>();

synchronized (list) {
    for (String element : list) {
        if (condition) {
            list.remove(element);
        }
    }
}

2.4 Using CopyOnWriteArrayList
CopyOnWriteArrayList is a thread-safe collection class that creates a new collection copy during write (add, delete, modify) operations to avoid concurrent modification exceptions.

import java.util.concurrent.CopyOnWriteArrayList;

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("item1");
list.add("item2");

for (String element : list) {
    if (condition) {
        list.remove(element);
    }
}

3. Summary

Java concurrent modification exception (ConcurrentModificationException) is caused by multiple threads modifying collection class objects at the same time. In order to solve this problem, you can use the iterator's remove method, concurrent collection class, synchronization mechanism, or CopyOnWriteArrayList and other methods. Choose an appropriate method according to the actual situation to resolve concurrent modification exceptions and ensure the stability and reliability of the program.

4. Reference materials

  1. "How to solve ConcurrentModificationException in Java", Baeldung, https://www.baeldung.com/java-concurrentmodificationexception
  2. " ConcurrentModificationException in Java – How to avoid it?", JournalDev, https://www.journaldev.com/378/how-to-avoid-concurrentmodificationexception-in-java

The above is the detailed content of How to solve Java concurrent modification exception (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