java - 奇怪的 Java 并发修改异常示例

标签 java exception

<分区>

如果我们这样写,就会出现并发修改异常:

public static void main(String... args) {
    List<String> listOfBooks = new ArrayList<>();
    listOfBooks.add("Programming Pearls");
    listOfBooks.add("Clean Code");
    listOfBooks.add("Effective Java");
    listOfBooks.add("Code Complete");

    System.err.println("Before deleting : " + listOfBooks);
    for (String book : listOfBooks) {
        if (book.contains("Code")) {
            listOfBooks.remove(book);
        }
    }
    System.err.println("After deleting : " + listOfBooks);
}

另一方面,如果我们这样写,没有并发修改异常! 请注意代码完全相同,除了用于比较的字符串,在第一个示例中它是一个 Code,在第二个示例中它是一个 Java

public static void main(String... args) {
    List<String> listOfBooks = new ArrayList<>();
    listOfBooks.add("Programming Pearls");
    listOfBooks.add("Clean Code");
    listOfBooks.add("Effective Java");
    listOfBooks.add("Code Complete");

    System.err.println("Before deleting : " + listOfBooks);
    for (String book : listOfBooks) {
        if (book.contains("Java")) {
            listOfBooks.remove(book);
        }
    }
    System.err.println("After deleting : " + listOfBooks);
}

我正在使用 Netbeans 8.2、Windows 7 32 位和 JDK 1.8.0_131 怎么了?

最佳答案

List.remove() 从列表中删除倒数第二个元素时不会抛出 ConcurrentModificationException

引自此Java Bug (JDK-4902078) .

When the Collections Framework was added to the platform it was deemed too expensive to check for comodification once rather than twice per iteration; the check was made on Iterator.next rather than Iterator.hasNext. Expert reviewers thought this was sufficient. They were unaware that it fails to detect one important case: if an element is removed from the list immediately prior to the final call to hasNext in an iteration, the call returns false and the iteration terminates, silently ignoring the last element on the list.

你也可以检查这个答案:-

https://stackoverflow.com/a/8189786/1992276

关于java - 奇怪的 Java 并发修改异常示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52689189/

相关文章:

c# - 在这种情况下如何使用异常?

java - 如何在另一个线程中重新抛出异常以捕获 block

java - 具有多个参数的 JNI 自定义异常

c# - 异常未处理 - 重新抛出异常

java - 如何在模型级别清理包含 HTML 的字符串字段?

java - 如何像浏览器一样在 Java 中组合 URL 片段?

java - 读取和写入共享线程变量

php - PHP 中内置了哪些异常子类?

java - 获取 SWT View 的大小

java - 我无法删除工具栏上的图标