gpt4 book ai didi

java - HashMap 不同步那么并发修改异常的原因

转载 作者:搜寻专家 更新时间:2023-11-01 02:03:07 24 4
gpt4 key购买 nike

HashMap 不应该是线程安全的,那么如果有人修改了 hashMap,为什么迭代器会抛出 concurrentmodificationexception

ConcurrentHashMap 也不会抛出这个异常。

Iterator 实现对于不同的数据结构是否不同,或者这些数据结构中是否存在抛出 ConcurrentModificationException

的方法?

最佳答案

HashMap 的结构被修改(即添加或删除条目)时 HashMap 正在被迭代,迭代器可能会以多种方式失败。

ConcurrentModificationException 异常旨在使任何迭代器因此类修改而快速失败。

这就是 modCount 字段的用途:

/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;

此行为并非特定于 MapCollection 在迭代期间被修改时也会抛出此异常。

关于java - HashMap 不同步那么并发修改异常的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40883143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com