一、简介
fail-fast 机制是java集合(Collection)中的一种错误机制。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。即:当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了(即其它线程通过add、remove、clear等方法,改变了modCount的值);那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件。
// AbstractList中唯一的属性
// 用来记录List修改的次数:每修改一次(添加/删除等操作),将modCount+1
protected transient int modCount = 0;
二、 fail-fast 解决方式
fail-fast机制,是一种错误检测机制。它只能被用来检测错误,因为JDK并不保证fail-fast机制一定会发生。若在多线程环境下使用fail-fast机制的集合,建议使用“java.util.concurrent包下的类”去取代“java.util包下的类”。
例如:private static List<String> list = new ArrayList<String>();
替换为:private static List<String> list = new CopyOnWriteArrayList<String>();
即保证了线程安全。
借鉴博客:https://www.cnblogs.com/skywang12345/p/3308762.html