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=" ...
随机推荐
- .Net分布式锁
项目中一般使用lock作为锁,以便于多线程操作确保库内数据统一.但是如果分布式部署项目,则这种锁就是去了意义,这时可以使用redis或memcache的add方法作为分布式锁. 栗子
- UTC时间戳转为时间
/// <summary> /// 将UTC时间转化DateTime时间 /// </summary> /// <returns></returns> ...
- 如何保证Redis的高可用
什么是高可用 全年时间里,99%的时间里都能对外提供服务,就是高可用 主备切换 在master故障时,自动检测,将某个slave切换为master的过程,叫做主备切换.这个过程,实现了Redis主从架 ...
- 一个良好划分Activity创建步骤的BaseActivity
一个Activity的创建过程其实包含几个不同的步骤,基本上都是在onCreate函数中完成的,这些步骤主要有: 设置页面的布局文件 初始化页面包含的控件 设置页面控件的点击响应事件 处理页面的业务逻 ...
- [LeetCode] Best Time to Buy and Sell Stock 6道合集【DP】
1. Best Time to Buy and Sell Stock 2. Best Time to Buy and Sell Stock II 3. Best Time to Buy and Sel ...
- node.js版本管理
Node安装 Node的安装需要依赖很多,如gcc等,首先我们需要将这些安装成功,用rpm命令查看下,果然我们并没有gcc等,所以要用yum进行安装(基于centos6.9版本): yum -y in ...
- Python 实现红绿灯
一.通过Event来实现两个或多个线程间的交互,下面是一个红绿灯的例子,即起动一个线程做交通指挥信号灯,一个线程做车辆,车辆行驶按红灯停,绿灯行的规则. #!/usr/bin/python # -*- ...
- Codeforces 542E Playing on Graph 其他
原文链接https://www.cnblogs.com/zhouzhendong/p/CF542E.html 题目传送门 - CF542E 题目传送门 - 51Nod1481 题意 有一幅无向图,它有 ...
- 2018牛客网暑假ACM多校训练赛(第四场)E Skyline 线段树 扫描线
原文链接https://www.cnblogs.com/zhouzhendong/p/NowCoder-2018-Summer-Round4-E.html 题目传送门 - https://www.no ...
- 用vs调式docker环境下web程序的一处坑
新建web项目,此时launchSettings.json文件为: "iisSettings": { "windowsAuthentication": fals ...