fast-fail事件的产生及其解决办法
1、fail-fast事件出现的情景
import java.util.*;
import java.util.concurrent.*; /*
*
*
* fail-fast事件产生的条件:当多个线程对Collection进行操作时,若其中某一个线程通过iterator去遍历集合时,该集合的内容被其他线程所改变;则会抛出ConcurrentModificationException异常。
* fast-fail解决办法:通过util.concurrent集合包下的相应类去处理,则不会产生fail-fast事件。
*
* 本例中,分别测试ArrayList和CopyOnWriteArrayList这两种情况。ArrayList会产生fast-fail事件,而CopyOnWriteArrayList不会产生fail-fast事件。
* (01) 使用ArrayList时,会产生fail-fast事件,抛出ConcurrentModificationException异常;定义如下:
* private static List<String> list = new ArrayList<String>();
* (02) 使用时CopyOnWriteArrayList,不会产生fail-fast事件;定义如下:
* private static List<String> list = new CopyOnWriteArrayList<String>();
*
*/
public class FastFailTest { private static List<String> list = new ArrayList<String>();
//private static List<String> list = new CopyOnWriteArrayList<String>();
public static void main(String[] args) { // 同时启动两个线程对list进行操作!
new ThreadOne().start();
new ThreadTwo().start();
} private static void printAll() {
System.out.println(""); String value = null;
Iterator iter = list.iterator();
while(iter.hasNext()) {
value = (String)iter.next();
System.out.print(value+", ");
}
} /**
* 向list中依次添加0,1,2,3,4,5,每添加一个数之后,就通过printAll()遍历整个list
*/
private static class ThreadOne extends Thread {
public void run() {
int i = 0;
while (i<6) {
list.add(String.valueOf(i));
printAll();
i++;
}
}
} /**
* 向list中依次添加10,11,12,13,14,15,每添加一个数之后,就通过printAll()遍历整个list
*/
private static class ThreadTwo extends Thread {
public void run() {
int i = 10;
while (i<16) {
list.add(String.valueOf(i));
printAll();
i++;
}
}
} }
运行该代码,抛出异常java.util.ConcurrentModificationException!即,产生fail-fast事件!
2、fail-fast的简单介绍
fail-fas机制是Java集合中的一种错误检测,当多个线程对同一个集合进行操作的时候,就可能会产生这样的错误。举例来说:当某一个线程A通过Iterator遍历集合的过程中,若该集合中的内容被另外一个线程改变了,那么当线程A在遍历集合的过程中就会出现ConcurrentModificationException异常,这就是产生了产生fail-fast事件。
3、fail-fast的产生原理
产生fail-fast事件,是通过抛出ConcurrentModificationException异常来触发的。
那么,ArrayList是如何抛出ConcurrentModificationException异常的呢?
我们知道,ConcurrentModificationException是在操作Iterator时抛出的异常。我们先看看Iterator的源码。ArrayList的Iterator是在父类AbstractList.java中实现的。代码如下:
package java.util; public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { ... // AbstractList中唯一的属性
// 用来记录List修改的次数:每修改一次(添加/删除等操作),将modCount+1
protected transient int modCount = 0; // 返回List对应迭代器。实际上,是返回Itr对象。
public Iterator<E> iterator() {
return new Itr();
} // Itr是Iterator(迭代器)的实现类
private class Itr implements Iterator<E> {
int cursor = 0; int lastRet = -1; // 修改数的记录值。
// 每次新建Itr()对象时,都会保存新建该对象时对应的modCount;
// 以后每次遍历List中的元素的时候,都会比较expectedModCount和modCount是否相等;
// 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
int expectedModCount = modCount; public boolean hasNext() {
return cursor != size();
} public E next() {
// 获取下一个元素之前,都会判断“新建Itr对象时保存的modCount”和“当前的modCount”是否相等;
// 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
} 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();
}
} final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
} ...
}
从中,我们可以发现在调用 next() 和 remove()时,都会执行 checkForComodification()函数。若 “modCount 不等于 expectedModCount”,就会抛出ConcurrentModificationException异常,产生fail-fast事件。
要搞明白 fail-fast机制,我们就要需要理解什么时候“modCount 不等于 expectedModCount”!
从Itr类中可以得知 expectedModCount的值在创建Itr对象时被赋值为 modCount。通过Itr,expectedModCount不可能被修改为不等于 modCount。所以,需要考证的就是modCount何时会被修改。
接下来,我们查看ArrayList的源码,来看看modCount是如何被修改的。
package java.util; public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{ ... // list中容量变化时,对应的同步函数
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
} // 添加元素到队列最后
public boolean add(E e) {
// 修改modCount
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
} // 添加元素到指定的位置
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size); // 修改modCount
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
} // 添加集合
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
// 修改modCount
ensureCapacity(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
} // 删除指定位置的元素
public E remove(int index) {
RangeCheck(index); // 修改modCount
modCount++;
E oldValue = (E) elementData[index]; int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null; // Let gc do its work return oldValue;
} // 快速删除指定位置的元素
private void fastRemove(int index) { // 修改modCount
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
} // 清空集合
public void clear() {
// 修改modCount
modCount++; // Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null; size = 0;
} ...
}
从中,我们发现:无论是add()、remove(),还是clear(),只要涉及到修改集合中的元素个数时,都会改变modCount的值。
接下来,我们再系统的梳理一下fail-fast是怎么产生的。步骤如下:
(01) 新建了一个ArrayList,名称为arrayList。
(02) 向arrayList中添加内容。
(03) 新建一个“线程a”,并在“线程a”中通过Iterator反复的读取arrayList的值。
(04) 新建一个“线程b”,在“线程b”中删除arrayList中的一个“节点A”。
(05) 这时,就会产生有趣的事件了。
在某一时刻,“线程a”创建了arrayList的Iterator。此时“节点A”仍然存在于arrayList中,创建arrayList时,expectedModCount = modCount(假设它们此时的值为N)。在“线程a”在遍历arrayList过程中的某一时刻,“线程b”执行了,并且“线程b”删除了arrayList中的“节点A”。“线程b”执行remove()进行删除操作时,在remove()中执行了“modCount++”,此时modCount变成了N+1!“线程a”此时会接着遍历,当它执行到next()函数时,调用checkForComodification()函数比较“expectedModCount”和“modCount”的大小;而“expectedModCount=N”,“modCount=N+1”两者不再相等,这样就会抛出ConcurrentModificationException异常,产生fail-fast事件。
4、fail-fast的解决办法
若在多线程环境下使用fail-fast机制的集合,建议使用“java.util.concurrent包下的类”去取代“java.util包下的类”。所以,本例中只需要将ArrayList替换成java.util.concurrent包下对应的类即可。
将
private static List<String> list = new ArrayList<String>();
改为:
private static List<String> list = new CopyOnWriteArrayList<String>();
就可以解决问题。
关于ArrayList和CopyOnWriteArrayList的小总结:
(01) 和ArrayList继承于AbstractList不同,CopyOnWriteArrayList没有继承于AbstractList,它仅仅只是实现了List接口。
(02) ArrayList的iterator()函数返回的Iterator是在AbstractList中实现的;而CopyOnWriteArrayList是自己实现Iterator。
(03)
ArrayList的Iterator实现类中调用next()时,会“调用checkForComodification()比较‘expectedModCount’和‘modCount’的大小”;但是,CopyOnWriteArrayList的Iterator实现类中,没有所谓的checkForComodification(),更不会抛出ConcurrentModificationException异常!CopyOnWriteArrayList不会抛ConcurrentModificationException,是因为所有改变其内容的操作(add、remove、clear等),都会copy一份现有数据,在现有数据上修改好,在把原有数据的引用改成指向修改后的数据。而不是在读的时候copy。
fast-fail事件的产生及其解决办法的更多相关文章
- jQuery绑定和解绑点击事件及重复绑定解决办法
原文地址:http://www.111cn.net/wy/jquery/47597.htm 绑点击事件这个是jquery一个常用的功能,如click,unbind等等这些事件绑定事情,但还有很多朋友不 ...
- webview滑动事件 与内部html左右滑动事件冲突问题的解决办法
最近在做个混合app , 用html做页面,然后通过webview嵌套在activity中,效果是这样: 开始还是比较顺利,增加了菜单退出按钮,返回键页面回退功能,页面加载显示加载图标(在app端实现 ...
- IOS设备上给body绑定click事件不生效及其解决办法
事件背景: 最近在做一个移动端业务的时候碰到一个bug,在ios上对body绑定click事实现事件代理冒泡至某些元素上尽然不生效. 思考: 暂借助jquery展示下事件绑定代码,将所有标签含有dat ...
- IOS中input键盘事件keyup 的兼容解决办法
用input监听键盘keyup事件,在安卓手机浏览器中是可以的,但是在ios手机浏览器中很慢,用输入法输入之后,并未立刻相应keyup事件. 解决办法: 在ios设备上可以用html5的input事件 ...
- Iphone上对于动态生成的html元素绑定点击事件$(document).click()失效解决办法
在Iphone上,新生成的DOM元素不支持$(document).click的绑定方法,该怎么办呢? 百度了N久都没找到解决办法,在快要走投无路之时,试了试Google,我去,还真找到了,歪国人就是牛 ...
- IScroll中div点击事件触发两次解决办法
1.网上的同学说的,直接修改源代码,但是这种方法可能会影响到现有的程序. 搜索onBeforeScrollStart方法,将其中的preventDefault禁止掉搜索_end方法,将其中模拟clic ...
- android ListView中button点击事件盖掉onItemClick解决办法
ListView 1.在android应用当中,很多时候都要用到listView,但如果ListView当中添加Button后,ListView 自己的 public void onItemClick ...
- IOS7 UITableView一行滑动删除后 被删除行的下一行的点击事件将被忽略解决办法
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSI ...
- jquery添加未来元素时,其绑定事件不起作用解决办法
delegate说起对未来元素是其作用的,于是写下代码: <!DOCTYPE HTML> <html> <head> <meta charset=" ...
随机推荐
- IntelliJ IDEA 中自动生成 serialVersionUID 的方法
as, idea plugin中搜如下关键字,并安装该插件: GenerateSerialVersionUID 如上图所示,创建一个类并实现Serializable接口,然后按alt+Enter键,即 ...
- Android Https双向认证 + GRPC
keywords:android https 双向认证android GRPC https 双向认证 ManagedChannel channel = OkHttpChannelBuilder.for ...
- fcagte.exe应用程序错误
原文:What is Fcagte.exe and How To Fix It? Overview of Fcagte.exe What Is Fcagte.exe? Fcagte.exe is a ...
- Git Flow,Git团队协作最佳实践
规范的Git使用 Git是一个很好的版本管理工具,不过相比于传统的版本管理工具,学习成本比较高, 实际开发中,如果团队成员比较多,开发迭代频繁,对Git的应用比较混乱,会产生很多不必要的冲突或者代码丢 ...
- haoi2018
题解: 题目相对其他省难一点 不过弱省省选知识点都这么集中的么.. 4道数学题... 1.[HAOI2018]奇怪的背包 这题考场做就gg了... 其实我想到了那个性质.. 就是这个一定要是gcd的倍 ...
- WPF数据爬取小工具-某宝推广位批量生成,及订单爬取 记:接单最痛一次的感悟
项目由来:上月闲来无事接到接到一个单子,自动登录 X宝平台,然后重定向到指定页面批量生成推广位信息:与此同时自动定时同步订单数据到需求提供方的Java服务. 当然期间遇到一个小小的问题就是界面样式的问 ...
- asp.net core 2.0 webapi集成signalr
asp.net core 2.0 webapi集成signalr 在博客园也很多年了,一直未曾分享过什么东西,也没有写过博客,但自己也是汲取着博客园的知识成长的: 这两天想着不能这么无私,最近.N ...
- Python_生成器generator
生成器:调用时返回一个迭代器 如果一个函数中包含yield语法,那这个函数就会变成一个生成器 例1: def draw_money(draw): #这个函数称为生成器 while draw >0 ...
- Python_dict部分功能介绍
字典是无序的 x.clear():清除所有元素 x.fromkeys():返回一个新的字典,使前面的key=value x.get():如果k不存在,默认返回一个值,如果存在,则返回存在的值 x.it ...
- asp gridview
<table> <tr> <td colspan="5">请选择试卷制定人员<span style="color:red&quo ...