概述
当 HashMap 在迭代过程中,结构发生变化时,会抛出 ConcurrentModificationException 错误,称为快速失败机制。
对 HashMap 进行迭代:Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
Q:HashMap 是如何实现 fail-fast 机制的?
1. HashMap 会维护一个 modCount 变量,当 HashMap 中的结构发生变化(映射数量改变了或者发生了 rehash) 时,这个值会发生自增操作(putval、removeNode、
clear、computeIfAbsent、compute、merge 方法)
注:clear 和 removeNode 方法 modCount 也是自增,而不是自减
2. 在使用迭代器进行迭代时,每次迭代一个新节点之前都会判断 expectModCount 是否等于 modCount,不相等则抛出异常
执行顺序如下:
1. entrySet 会返回一个EntrySet 对象,调用其 iterator 方法,会返回一个 EntryIterator 对象
2. EntryIterator 对象继承了 HashIterator 实现了 Iterator,它有一个 next 方法,会调用 HashIterator 的 nextNode 方法,返回下一个节点
3. 在 nextNode 方法中首先会判断 expectModCount 和 modCount 是否相等,不相等则会抛出 concurrentModificationException 异常
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();
// 这个判断是当前遍历到了下标为 index 的链表或者红黑树的最后一个节点
if ((next = (current = e).next) == null && (t = table) != null) {
// 找到下一个存储了键值对的下标 index
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
3. 在 forEach 方法中也会抛出 concurrentModificationException,不过与迭代器不同的是,它是会遍历完整个 HashMap 之后才会抛出这个异常,即对 expectModCount 和 modCount 的比较是在遍历完成之后
public void forEach(BiConsumer<? super K, ? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
// 遍历元素
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key, e.value);
}
// 对元素遍历完才进行比较
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
Q:如何防止 HashMap 遍历过程中抛出 ConcurrentModificationException 异常?
1. 使用迭代器的 remove 方法。即内部类 HashIterator 中的 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 中 modCount 的值自增了
removeNode(hash(key), key, null, false, false);
// 重新赋值
expectedModCount = modCount;
}
2. 使用 ConcurrentHashMap
总结:HashMap 在多线程中的迭代不是线程安全的,可能会抛出 ConcurrentModificationException 异常
参考博客:https://blog.csdn.net/zymx14/article/details/78394464
最后
以上就是友好服饰为你收集整理的HashMap 中的 fail-fast(快速失败机制)的全部内容,希望文章能够帮你解决HashMap 中的 fail-fast(快速失败机制)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复