java.util.ConcurrentModificationException 原因分析及解决方案

本文通过一个HashMap遍历删除元素的例子,深入分析了java.util.ConcurrentModificationException异常产生的原因,并提供了两种解决方案:使用Iterator自带的remove方法和采用线程安全的容器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

码代码的时候发现了这个异常,java.util.ConcurrentModificationException,倒是很熟悉,非线程安全的容器被非法修改了,具体什么原因呢,怎么避免呢,本文简单分析一下,这个小问题其实反映了对容器实现理解的不深刻。

首先,本着从源头找问题的原则,贴一下错误代码:

String str = "test";
Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
while(it.hasNext()){
    Map.Entry<String, String> entry=it.next();
    if (str.equals(params.get(entry.getKey()))) {
        params.remove(entry.getKey());
    }
}

这是一个hashmap的demo,上面可以清晰的看到,在遍历的过程中,符合条件的记录需要被删掉。我们想当然的使用了容器直接remove的方法。这时候得到了java.util.ConcurrentModificationException异常。

定位一下问题,很明显是出在remove这一行。调查了一下,对于非线程安全的容器,这么搞是不可以的,为啥呢,我们先看下Iterator的next()方法:

final class EntryIterator extends HashIterator
        implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() { return nextNode(); }
    }

final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)//重点在这里
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

找到重点了,抛出异常的地方在nextNode比较modCount和expectedModCount的地方。

那再看下mocCount什么时候增加,增加对象的时候增加很好理解,但是减少的时候的呢,看代码,以下是HashMap.remove(Object) 的实现方法:

final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;//重点在这里
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

可以看到modCount增加了,但是没expectedModCount什么事,自然而然也就不想等了。

那我们再看下iterator自带的remove方法:

public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;//update expectedModCount
        }

这里就把expectedModCount更新了。那么对比起来就没问题了。

所以到这里,我们就找到原因所在了。找到问题,解决起来就方便了。

那么简单说一下解决方案吧:

1.使用iterator的remove,是安全的。从上面的代码中可以看出来,不再多说。

2.使用线程安全的ConcurrentHashMap或者Collections.synchronizedMap(Map<k,v>)

 

问题解决了,举一反三的来看,对于其他非线程安全的list,set,map也都使用了fail-fast,也都会有这个问题。使用的时候需要注意了。

### Java.util.ConcurrentModificationException 在 PHP 上下文中的相关性和解决方案 尽管 `java.util.ConcurrentModificationException` 是 Java 编程语言中特有的异常,但其核心问题——在迭代集合时修改集合结构——在 PHP 中同样存在。PHP 的数组和某些集合类(如 `SplDoublyLinkedList` 或 `ArrayObject`)也可能会遇到类似的问题。以下将详细分析该问题在 PHP 中的可能表现形式及解决方案。 #### 1. PHP 中的集合修改问题 在 PHP 中,直接修改数组或集合对象的结构(例如添加、删除元素)时,如果操作发生在迭代过程中,则可能导致意外行为或错误。虽然 PHP 不会抛出类似于 Java 的 `ConcurrentModificationException`,但可能会出现逻辑错误或未定义行为[^4]。 以下是一个示例代码: ```php $array = ['One', 'Two', 'Three']; foreach ($array as $key => $value) { if ($value === 'Two') { unset($array[$key]); // 在迭代过程中直接修改数组 } } print_r($array); ``` 上述代码中,`unset` 操作可能会导致迭代器跳过某些元素,从而引发逻辑错误[^5]。 #### 2. 解决方案 以下是几种常见的解决方法,用于避免在 PHP 中迭代集合时修改集合结构带来的问题。 ##### (1) 使用临时数组存储修改 在迭代过程中,将需要修改的元素记录到一个临时数组中,待迭代结束后再统一处理。 ```php $array = ['One', 'Two', 'Three']; $toRemove = []; foreach ($array as $key => $value) { if ($value === 'Two') { $toRemove[] = $key; // 记录需要移除的键 } } foreach ($toRemove as $key) { unset($array[$key]); // 统一移除 } print_r($array); ``` ##### (2) 使用引用传递 通过引用传递的方式,可以在迭代过程中安全地修改数组内容。 ```php $array = ['One', 'Two', 'Three']; foreach ($array as $key => &$value) { if ($value === 'Two') { $value = null; // 修改值而不是删除键 } } unset($value); // 确保引用解除 $array = array_filter($array, function($val) { return $val !== null; // 过滤掉被标记为 null 的值 }); print_r($array); ``` ##### (3) 使用 `SplDoublyLinkedList` 或其他集合类 PHP 提供了标准库(SPL)中的集合类,例如 `SplDoublyLinkedList`,这些类可以更安全地处理迭代和修改操作。 ```php $deque = new SplDoublyLinkedList(); $deque->push('One'); $deque->push('Two'); $deque->push('Three'); while (!$deque->isEmpty()) { $item = $deque->shift(); // 安全地移除头部元素 if ($item === 'Two') { continue; // 跳过不需要的元素 } echo $item . PHP_EOL; } ``` #### 3. 多线程环境下的注意事项 虽然 PHP 默认是单线程的,但在使用多线程扩展(如 `pthreads` 或 `parallel`)时,仍需注意集合的并发修改问题。建议在多线程环境中使用线程安全的数据结构或加锁机制来确保一致性[^6]。 以下是一个使用锁机制的示例: ```php $mutex = new Mutex(); $array = ['One', 'Two', 'Three']; $worker = new class($mutex, $array) extends Thread { private $mutex; private $array; public function __construct($mutex, $array) { $this->mutex = $mutex; $this->array = $array; } public function run() { $this->mutex->synchronized(function() { foreach ($this->array as $key => $value) { if ($value === 'Two') { unset($this->array[$key]); // 安全地修改数组 } } }); } }; $worker->start(); $worker->join(); print_r($array); ``` --- ### 总结 虽然 PHP 不会抛出类似于 Java 的 `ConcurrentModificationException`,但在迭代集合时修改集合结构仍然可能导致逻辑错误或未定义行为。为了避免这些问题,可以使用临时数组存储修改、引用传递、SPL 集合类或加锁机制等方法来确保集合操作的安全性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值