首页 技术 正文
技术 2022年11月7日
0 收藏 391 点赞 862 浏览 1753 个字

快速失败是指某个线程在迭代集合类的时候,不允许其他线程修改该集合类的内容,这样迭代器迭代出来的结果就会不准确。

比如用iterator迭代collection的时候,iterator就是另外起的一个线程,它去迭代collection,如果此时用collection.remove(obj)这个方法修改了collection里面的内容的时候,就会出现ConcurrentModificationException异常,这时候该迭代器就快速失败。

代码如下:

package com.vino.assemble;import java.util.ArrayList;
import java.util.List;/**
* show fail fast in in the hashmap
* @author haowei.yu
*
*/
public class FailFastDemo {
public static void main(String[] args) {
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(1);
tempList.add(2);
tempList.add(3);
tempList.add(4);
tempList.add(5);
tempList.add(1); //use iterator to travel the list and remove the value equals to 1 for(int temp: tempList){
if(temp == 1){
tempList.remove(temp);
}
}
}
}

这样运行程序,就会抛出java.util.ConcurrentModificationException异常。

这样做的好处是:对于非并发集合,在用迭代器对其迭代时,若有其他线程修改了增减了集合中的内容,这个迭代会马上感知到,并且立即抛出 ConcurrentModificationException 异常,而不是在迭代完成后或者某些并发的场景才报错。具体这样的机制在java里是怎么实现的呢?其实很简单,是通过modCount域来实现的。modCount顾名思义是修改次数,对List内容的修改都会增加这个值,在迭代器初始化的过程中会将这个值赋值给迭代器的expectedModCount。我们来看ArrayList和Iterator的源码,注释已经写的听清楚了,这里就不解释了。

//ArrayList的源码
protected transient int modCount = 0; //In AbstractList class,provider fail-fast iterators.note that this field is transientpublic boolean add(E e) {
modCount++; // Increments modCount!!
.....
return true;
}public E remove(int index) {
....
modCount++; // Increments modCount!!
....
return oldValue;
}//Iterator的源码int expectedModCount = modCount; // iterator believes the backing list should hava.
public void remove() {
try {
....
if (modCount != expectedModCount)// judge the modCount equals with expectedModCount.
throw new ConcurrentModificationException();
...
}
}

TIPS:

  • 在迭代器创建之后,如果从结构上对映射进行修改,除非通过迭代器本身的 remove 方法,其他任何时间任何方式的修改,迭代器都将抛出ConcurrentModificationException。
  • 迭代器的快速失败行为不能得到保证,一般来说,存在非同步的并发修改时,不可能作出任何的保证。快速失败迭代器只是尽最大努力抛出ConcurrentModificationException。因此,编写依赖于此异常的程序的做法是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,030
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,147
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,859