📜  Java如何解决ConcurrentModificationException?

📅  最后修改于: 2021-10-28 02:30:27             🧑  作者: Mango

扰乱程序正常流程的未被接受的、不需要的事件称为异常。大多数时候异常是由我们的程序引起的,这些都是可以恢复的。示例:如果我们的程序要求是从位于美国的远程文件中读取数据 在运行时,如果远程文件不可用,那么我们将收到 RuntimeException 说 FileNotFoundException。如果发生 FileNotFoundException,我们可以将本地文件提供给程序以正常读取并继续程序的其余部分。

Java的异常主要有以下两种:

  1. Checked Exceptions是编译器为了程序在运行时的顺利执行而检查的异常,称为Checked Exception 。在我们的程序,如果有检查的异常上升,然后强制我们应该处理检查异常的机会(通过try-catch代码或抛出的关键字),否则,我们将得到一个编译时错误。
  2. Unchecked Exceptions是编译器未检查的异常,无论程序员处理与否,此类异常都称为未检查异常。 unchecked异常的例子是ArithmeticException,ArrayStoreException信息

执行:

ConcurrentModificationException是 RuntimeException 的子类,因此它是一个未经检查的异常。当一个对象在不允许的情况下被尝试并发修改时会出现此异常,即当一个线程正在迭代某个集合类对象并且如果某个其他线程试图修改或尝试对该集合对象进行一些更改时,我们将得到并发修改异常。当我们使用Java集合类时,通常会发生此异常。

例子

Java
// Java program to illustrate
// ConcurrentModificationException
 
// Importing all classes from java.util package
// Importing input output classes
import java.io.*;
import java.util.*;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of ArrayList
        // Declaring object of Integer type
        ArrayList list = new ArrayList<>();
 
        // Adding element to ArrayList object created above
        // using the add() method
        // Custom input elements
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
 
        // Display all the elements of ArrayList object
        System.out.println("List Value Before Iteration:"
                           + list);
 
        // Creating an iterator object to
        // iterate over the ArrayList
        Iterator it = list.iterator();
 
        // Condition check
        // It holds true till there is single element
        // remaining in the List
        while (it.hasNext()) {
            Integer value = it.next();
 
            // Here we are trying to remove the one entry of
            // ArrayList base on the if condition and hence
 
            // We will get Concurrent ModificationException
            if (value.equals(3))
                list.remove(value);
        }
 
        // Print and display the value of ArrayList object
        System.out.println("List Value After Iteration:"
                           + list);
    }
}


Java
// Java Program to illustrate
// ConcurrentModificationException
 
// Importing the required packages
import java.io.*;
import java.util.*;
import java.util.Iterator;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an collection class object
        // Declaring object of integer type
        ArrayList list = new ArrayList<>();
 
        // Adding element to ArrayList
        // using add() method
 
        // Custom integer input entries
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
 
        // Display the value of ArrayList
        System.out.println("List Value Before Iteration:"
                           + list);
 
        // Creating an iterator object
        // to iterate over the ArrayList
        Iterator itr = list.iterator();
 
        // Condition check
        // it holds true till there is single element
        // remaining in the List
        while (itr.hasNext()) {
 
            // next() method() loos out for next element in
            // the List
            Integer value = itr.next();
 
            // Here we are trying to remove the one entry of
            // ArrayList base on the given if condition and
            // hence
 
            // We will get Concurrent ModificationException
            if (value.equals(3))
                itr.remove();
        }
        // Display the value of ArrayList
        System.out.println("List Value After iteration:"
                           + list);
    }
}


输出:

输出说明:

上面的程序是一个单线程程序,这里我们可以通过使用迭代器的remove()函数来避免ConcurrentModificationException,我们可以从底层集合对象中删除一个对象而不会出现任何异常。

示例 2

Java

// Java Program to illustrate
// ConcurrentModificationException
 
// Importing the required packages
import java.io.*;
import java.util.*;
import java.util.Iterator;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an collection class object
        // Declaring object of integer type
        ArrayList list = new ArrayList<>();
 
        // Adding element to ArrayList
        // using add() method
 
        // Custom integer input entries
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
 
        // Display the value of ArrayList
        System.out.println("List Value Before Iteration:"
                           + list);
 
        // Creating an iterator object
        // to iterate over the ArrayList
        Iterator itr = list.iterator();
 
        // Condition check
        // it holds true till there is single element
        // remaining in the List
        while (itr.hasNext()) {
 
            // next() method() loos out for next element in
            // the List
            Integer value = itr.next();
 
            // Here we are trying to remove the one entry of
            // ArrayList base on the given if condition and
            // hence
 
            // We will get Concurrent ModificationException
            if (value.equals(3))
                itr.remove();
        }
        // Display the value of ArrayList
        System.out.println("List Value After iteration:"
                           + list);
    }
}
输出
List Value Before Iteration:[1, 2, 3, 4, 5]
List Value After iteration:[1, 2, 4, 5]