Java集合框架之modCount属性(fail-fast快速失败机制)

modCount属性解析

相信大家在看集合框架的源码时都会发现一个特别的属性叫做modCount,会感觉这个属性存在感很低(或者没什么存在感),那么这个属性有什么用呢?

 protected transient int modCount = 0;

1.案例演示

接下来以ArrayList为例,演示一下出现的问题。

ArrayList示例

前导知识:集合的foreach循环遍历实际上还是迭代器(Iterator)遍历,具体参考

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            list.add("" + i);
        }
        //实际上还是迭代器遍历
        for (String s : list) {
            //迭代器遍历时对集合进行了add操作。
            list.add("sss");
            System.out.println(s);
        }
        
        /*  上面的foreach循环本质上就是下面的迭代器遍历
         *    Iterator<String> iterator = list.iterator();
      	 *	  while (iterator.hasNext()) {
         * 	  String next = iterator.next();
         *  	 System.out.println(next);
       	 *	  }
         */  
    }

//运行结果: 抛出并发修改异常
/*	Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:911)
	at java.util.ArrayList$Itr.next(ArrayList.java:861)
	at Yinyong.Main.main(Main.java:28)
*/

2.迭代器详解&modCount执行过程

以上面的代码为例,我们看一下ArrayList的迭代器是如何实现的

/* 当执行下面一行代码时,会构造一个迭代器对象 (new Itr())
 * Iterator<String> iterator = list.iterator(); 
 */
public Iterator<E> iterator() {
    	
        return new Itr();
 }

Itr类

此类是ArrayList类的一个内部类。

    private class Itr implements Iterator<E> {
        //当前元素索引
        int cursor;       
        //当前遍历到的元素索引
        int lastRet = -1; 
        //存ArrayList内部得modCount
        int expectedModCount = modCount;

        Itr() {}
		
        /*
         * -- hasNext()方法,判断是否还有元素。
         * 因为调用next()时,cursor每次往后移动,当cursor == size时,说明遍历完毕
         * (因为cursor是从0开始)
         */
        public boolean hasNext() {
            return cursor != size;
        }
		
        /*
         * 返回当前元素
         */
        public E next() {
            //此方法就是去检查modCount的情况。
            checkForComodification();
            //i存储当前将要遍历的元素的索引
            int i = cursor;
            //越界检查
            if (i >= size)
                throw new NoSuchElementException();
            //获取List内部的数组
            Object[] elementData = ArrayList.this.elementData;
            //i大于elementData.length 说明再次期间数组已经可能发生扩容了,抛异常
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            //cursor + 1,指针后移
            cursor = i + 1;
            //返回当前元素。
            return (E) elementData[lastRet = i];
        }  

核心之checkForComodification()方法

        final void checkForComodification() {
            /*检查创建迭代器对象时的modCount与当前modCount是否相同,
             *如果不同,说明当前在迭代遍历元素期间有其他线程对List进行了add或者remove
             *那么直接抛出异常。
             */
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

通过上面的对于Itr的分析,我们可以清晰的知道,当我们调用iterator()方法时,会创建一个Itr对象,此时会将ArrayList内部的modCount赋值给Itr(迭代器)内部的expectModCount赋值,然后每次调用next()方法获取迭代时都会检查此时modCount是否等于expectedModCount,不相等的话说明在遍历期间有其他线程(也可能是本线程)对ArrayList内部新增或者删除了元素,此时就会抛出ConcurrentModificationException,即并发修改异常。

3.什么情况会修改modCount的值

通过对上面的分析,我们知道了modCount的作用,那么做什么操作会修改modCount的值呢? 这里以ArrayList为例分析一下。

3.1增add()时会修改

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

//                ||
//				  ||
//				  \/
 private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

//                ||
//				  ||
//				  \/
    private void ensureExplicitCapacity(int minCapacity) {
        //修改modCount
        modCount++;
    }

3.2删remove()时会修改

    public E remove(int index) {

        modCount++;
		
        // ...省略
    }

3.3改set()时不会修改

    public E set(int index, E element) {
        rangeCheck(index); //检查索引是否越界
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

为什么修改元素不会改变modCount时,因为修改不会导致元素个数发生变化

看一下HashMap中的put操作,跟ArrayList也是相同的,只有添加(或者删除)了一个元素即对元素个数发生变化的操作才会修改modCount,修改操作没有改变元素个数所以不会修改modCount。

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
         			
        	//这里省略了四种情况
        	
        
        	/*
        	 * 这里是替换操作,没有修改modCount,只是将value
        	 * 替换后直接return了旧value。
        	 */
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }

		//能走到这说明是添加操作,同样修改了modCount。
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

4.fail-fast机制

什么是fail-fast

  • fail-fast机制是java集合中的一种错误机制。
  • 当使用迭代器迭代时,如果发现集合有修改,则快速失败做出响应,抛出ConcurrentModificationException异常。
  • 这种修改有可能是其它线程的修改,也有可能是当前线程自己的修改导致的,比如迭代的过程中直接调用remove()删除元素等。
  • 另外,并不是java中所有的集合都有fail-fast的机制。比如,像最终一致性的ConcurrentHashMap、CopyOnWriterArrayList等都是没有fast-fail的

那么,fail-fast是怎么实现的呢?

通过上面的讲解我们就可以清晰的知道它的实现原理,像ArrayList、HashMap中都有一个属性叫 modCount,每次对集合的修改这个值都会加1,在遍历前记录这个值到 expectedModCount中,遍历中检查两者是否一致,如果出现不一致就说明有修改,则抛出ConcurrentModificationException异常。

5.额外知识-LinkedList迭代器遍历避免fail-fast

参考

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shstart7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值