首頁 >Java >java教程 >在Java中使用迭代器時conturrentModification Exception

在Java中使用迭代器時conturrentModification Exception

DDD
DDD原創
2025-02-07 11:18:10731瀏覽

ConcurrentModificationException while using Iterator in Java

在多線程Java環境中,嘗試在使用迭代器上進行迭代時嘗試修改集合可以導致A

。由於收藏的內部狀態變得不一致,因此出現了此例外。 ConcurrentModificationException>

這是一個示例,說明了例外:

<code class="language-java">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)</code>
在以下情況下發生此例外:

在迭代過程中進行
    修改:迭代器不是為並發修改而設計的。
  • >失敗效率迭代器:迭代器使用內部標誌(
  • )來檢測修改並拋出異常。
  • modCount 用於復制異常的
算法

此算法演示瞭如何在Java中觸發a

ConcurrentModificationException

初始化:
    >創建
  1. ArrayList>人口:
  2. >添加元素
  3. 迭代:ArrayList>使用
  4. > 修改:在迭代循環中,修改list.iterator()(例如,添加或刪除元素)。
  5. 異常:>當迭代器檢測修飾時,被拋棄。 ArrayList
  6. >代碼示例:觸發異常ConcurrentModificationException>
此代碼將拋出

,因為在迭代器遍歷它時修改了列表。

<code class="language-java">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!
            }
        }
    }
}</integer></integer></code>
安全修改技術

ConcurrentModificationException myList.remove(value)避免這種例外,請使用以下方法:

在迭代過程中使用

>刪除元素的方法。此方法是安全的,因為它旨在與迭代器的內部狀態一起使用。
  • 複製列表:Iterator.remove()在迭代之前創建列表的副本並修改副本。 iterator.remove()

    >
  • 使用並發集合:
  • 用於並發修改方案,使用線程安全集合,例如

    >或>。

  • >同步塊:

    將迭代和修改包裝在同步塊中,以確保線程安全。 > CopyOnWriteArrayList ConcurrentHashMap

    >示例:使用
  • 安全去除安全 此修訂的代碼可以安全地刪除元素,而無需拋出異常。 請記住根據您的特定需求和並發要求選擇適當的技術。 對於多線程方案,使用並發集合通常是首選。

    >

以上是在Java中使用迭代器時conturrentModification Exception的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn