Home  >  Article  >  Java  >  How to deal with ConcurrentModificationException in Java?

How to deal with ConcurrentModificationException in Java?

王林
王林Original
2023-06-25 08:31:431698browse

How to deal with ConcurrentModificationException in Java?

In Java programming, ConcurrentModificationException is a very common exception. This exception often occurs when we use an iterator (Iterator) or an enhanced for loop (foreach) to loop through a collection. This article will introduce the cause and solution of this exception.

  1. Cause of exception

When we use an iterator to traverse a collection, if the elements in the collection are modified (added, deleted, etc.) during the traversal process, it will be thrown A ConcurrentModificationException exception occurred. The reason for this exception is that when the next() method of Iterator is called, it will compare whether the current modCount is equal to expectedModCount. If it is not equal, it means that the collection has changed during the iteration process, that is, when we add or delete to the collection element, the value of modCount will be changed, but the value of expectedModCount will not change, causing the two to be unequal, and a ConcurrentModificationException exception will be thrown.

  1. Solution

In order to avoid the occurrence of ConcurrentModificationException, we need to avoid modifying the collection elements when traversing the collection. Generally speaking, there are three solutions:

(1) Use an ordinary for loop to traverse

Using an ordinary for loop to traverse is a feasible solution, because we can operate the elements in the collection through subscripts, instead of using iterators. However, this method is more troublesome to use and requires a larger amount of code.

Sample code:

List<String> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++) {
    String str = list.get(i);
    // 对str进行操作
}

(2) Use Iterator’s remove method

If we must modify elements while traversing the collection, then we can use Iterator’s The remove method performs the deletion operation. This method can be used to delete the element returned by the last call to next() method without throwing ConcurrentModificationException.

Sample code:

List<String> list = new ArrayList<>();
Iterator<String> it = list.iterator();
while(it.hasNext()) {
    String str = it.next();
    if(str.equals("hello")) {
        it.remove();
    }
}

(3) Using CopyOnWriteArrayList

CopyOnWriteArrayList is a thread-safe collection. Its read-write separation feature ensures that when we add to the collection Or when deleting elements, it will not affect the thread that is traversing. When an element changes, CopyOnWriteArrayList creates a new copy of the data and then operates on it. Therefore, CopyOnWriteArrayList is suitable for scenarios where there is more reading and less writing.

Sample code:

List<String> list = new CopyOnWriteArrayList<>();
Iterator<String> it = list.iterator();
while(it.hasNext()) {
    String str = it.next();
    if(str.equals("hello")) {
        list.remove(str);
    }
}

The above are the common methods we use to avoid ConcurrentModificationException exceptions. In actual programming, in order to ensure the robustness and efficiency of the program, we need to select methods based on the actual situation.

The above is the detailed content of How to deal with ConcurrentModificationException in Java?. 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