fast-fail机制

什么是fail-fast

    “快速失败”也就是fail-fast,它是Java集合的一种错误检测机制。在集合中经常遇到 java.util.ConcurrentModificationException异常,而产生这个原因就是fail-fast,主要发生在集合的迭代输出时,而在此时可能这个集合的内部结构已经发生改变,所以快速失败迭代器会尽最大努力抛出ConcurrentModificationException,以防止未知结果的发生。产生条件有如下两种情况:
(1)假设存在两个线程(线程1、线程2),线程1通过Iterator在遍历集合A中的元素,在某个时候线程2修改了集合A的结构,那么这个时候程序就可能会抛出 ConcurrentModificationException 异常
(2)在同一集合A中,如果正在迭代遍历集合A时,同时修改集合中的内容,就会抛出 ConcurrentModificationException 异常

fail-fast产生实例

单个线程的操作,我们看如下实例:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("xiaotang");
        list.add("java");
        list.add("c++");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            if ("xiaotang".equals(str)) {
                list.remove(str);
            }
        }
        for (String str : list) {
            System.out.println(str);
        }
    }
}
大家觉的输出结果是什么?
java
c++
其实真实结果如下:
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at Test.main(Test.java:13)
xiaotang
为什么会是这样的结果,我们在后面再去详细说明,接着我们再看一个多个线程的产生fast-fail的事例.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
    private List<integer> list = new ArrayList<integer>();
    /**
     * 初始化集合
     */
    public void initList() {
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
    }
    /**
     * 执行线程1,遍历List集合,并设置线程休眠
     */
    public void executeMethod1() {
        new Thread(new Runnable() {
            public void run() {
                // TODO 自动生成的方法存根
                Iterator iterator = list.iterator();
                while (iterator.hasNext()) {
                    System.out.println(iterator.next());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    /**
     * 执行线程2,修改List集合
     */
    public void executeMethod2() {
        new Thread(new Runnable() {
            public void run() {
                // TODO 自动生成的方法存根
                list.remove(3);
            }
        }).start();
    }
    public static void main(String[] args) {
        Test test = new Test();
        test.initList();
        test.executeMethod1();
        test.executeMethod2();
    }
}</integer></integer>
这个程序运行结果如下:(需要说明的是,这种结果是可能发生的,不是一定)
   
0
Exception in thread "Thread-0" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at Test$1.run(Test.java:27)
    at java.lang.Thread.run(Unknown Source)  
产生的具体原因,我们会在下面详细讲到!

fast-fail产生过程以及原理分析

    我们查看AbstractList类就会发现有这样的变量:protected transient int modCount = 0;我们再看看其Iterator类,申明了expectedModeCount==modCount,判断是否产生了fast-fail,其实判断就是判断expectedModeCount是否与modCount相等.不相等就会产生fast-fail.所以在某个过程中,两个数值改变了就会导致不相等了。而在List中,add(),remove()等操作都会改变modCount,我们再来仔细的查看上面事例产生的具体原因。
     
 while (iterator.hasNext()) {
            String str = iterator.next();
            if ("xiaotang".equals(str)) {
                list.remove(str);
            }
        }
在迭代的过程中,会通过list.remove(str),我们点开remove()源码:
    public boolean remove(Object o) {
	if (o == null) {
            for (int index = 0; index < size; index++)
		if (elementData[index] == null) {
		    fastRemove(index);
		    return true;
		}
	} else {
	    for (int index = 0; index < size; index++)
		if (o.equals(elementData[index])) {
		    fastRemove(index);
		    return true;
		}
        }
	return false;
    }
点开 fastRemove(index)方法:
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }
可以看到,modCount的值在这里面增加了1.我们再来看看,iterator.next()做了什么:
	public E next() {
            checkForComodification();
	    try {
		E next = get(cursor);
		lastRet = cursor++;
		return next;
	    } catch (IndexOutOfBoundsException e) {
		checkForComodification();
		throw new NoSuchElementException();
	    }
	}
点开checkForComodification()方法:
	final void checkForComodification() {
	    if (modCount != expectedModCount)
		throw new ConcurrentModificationException();
	}
可以看到这个方法就是判断modCount是否与expectedMoCount是否相等.不相等就会抛出ConcurrentModificationException异常。终于找到了根本原因了。所以, 不推荐我们在遍历集合的时候,又去修改集合的结构,可以大家就会问了,如果我们就是要通过迭代,去找到集合的内容,然后去remove掉这个元素呢?我们可以通过如下方法:
  Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            if ("xiaotang".equals(str)) {
                iterator.remove();
            }
        }
看到区别没,通过iterator.remove()就可以了,此时就不会报错了!我们看看为什么这样行,打开AbstractList中Iterator的remove实现方法:
	public void remove() {
	    if (lastRet == -1)
		throw new IllegalStateException();
            checkForComodification();

	    try {
		AbstractList.this.remove(lastRet);
		if (lastRet < cursor)
		    cursor--;
		lastRet = -1;
		expectedModCount = modCount;
	    } catch (IndexOutOfBoundsException e) {
		throw new ConcurrentModificationException();
	    }
	}
可以看到它其实就是调用 List的remove方法,但是你再往后面看就会发现 expectedModCount=modCount,所以迭代器调用 next()的时候,判断的两个数值就相等了,就不会抛出异常了!那么我们要在遍历的时候,调用add(),set呢?很显然,在Iterator迭代器中没有这些方法,这时候我就需要通过 List.listIterator()去遍历,而不是还是通过 List.iterator遍历。好了,以上就是我分享的fast-fail,欢迎大家和我一起学习,一起讨论!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值