HashMap 中的 fail-fast(快速失败机制)

当 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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值