zoukankan      html  css  js  c++  java
  • modCount干嘛的

    在ArrayList、LinkedList、HashMap等等的内部增删改中我们总能看到modCount的身影,modCount字面意思就是修改次数,但为什么要记录modCount的修改次数呢?

    大家发现一个公共特点了吗?所有使用modCount属性的都是线程不安全的,为什么?说明这个玩意肯定和线程安全有关系。

    阅读源码,发现这玩意只有在本数据结构对应迭代器中才使用,以HashMap为例

     abstract class HashIterator {
            Node<K,V> next;        // next entry to return
            Node<K,V> current;     // current entry
            int expectedModCount;  // for fast-fail
            int index;             // current slot
    
            HashIterator() {
                expectedModCount = modCount;
                Node<K,V>[] t = table;
                current = next = null;
                index = 0;
                if (t != null && size > 0) { // advance to first entry
                    do {} while (index < t.length && (next = t[index++]) == null);
                }
            }
    
            public final boolean hasNext() {
                return next != null;
            }
    
            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;
            }
    
            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;
            }
        }

    我们知道 java.util.HashMap 不是线程安全的,因此如果在使用迭代器的过程中有其他线程修改了map,那么将抛出ConcurrentModificationException,这就是所谓fail-fast策略。这一策略在源码中的实现是通过 modCount 域,modCount 顾名思义就是修改次数,对HashMap 内容的修改都将增加这个值,那么在迭代器初始化过程中会将这个值赋给迭代器的 expectedModCount。在迭代过程中,判断 modCount 跟 expectedModCount 是否相等,如果不相等就表示已经有其他线程修改了 Map:注意到 modCount 声明为 volatile,保证线程之间修改的可见性。

  • 相关阅读:
    Linux命令之vi
    CentOS7 查看IP
    Linux下mysql的命令
    @RequestMapping注解的参数说明
    springboot处理不同域的前端请求
    vue-cli4 取消关闭eslint 校验代码
    springmvc请求乱码
    访问静态资源报404错误
    eclipse创建Maven项目时pom.xml报错
    spring中的xml配置文件里报错
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10657335.html
Copyright © 2011-2022 走看看