当前位置:网站首页>fail-fast和fail-safe
fail-fast和fail-safe
2022-06-10 16:00:00 【张志明(努力奋斗版)】
fail-fast(快速失败)
当我们在遍历集合元素的时候,经常会使用迭代器,但在迭代器遍历元素的过程中,如果集合的结构被改变的话,就会抛出异常,防止继续遍历。这就是所谓的快速失败机制。即:一旦发现遍历的同时其它人来修改 则立即抛异常。java.util包下面的所有的集合类都是快速失败的
我们可以通过迭代器来遍历list,Iterator是一个接口, ArrayList内部类实现Iterator接口来实现相关方法 代码如下所示 其中expectedModCount记录了刚开始使用Iterator遍历时ArrayList修改了几次 如果有4个元素 那么就是修改了4次 expectedModCount=4;在调用next()方法移动到下个元素时 都要首先调用checkForComodification()进行检查; modCount != expectedModCount 这两个值刚开始是相等的 都是4 -->int expectedModCount = modCount;
如果在迭代器遍历元素的时候,如果modCount这个值发生了改变,那么再次遍历时就会抛出异常。当我们对集合的元素的个数做出改变的时候,modCount的值就会被改变,如果删除,插入。但修改则不会。
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
fail-safe (安全失败)
当我们对集合结构上做出改变的时候,对于采用fail-safe机制来说,不会抛出异常.即:发现遍历的同时其它人来修改 应当能有应对策略 例如牺牲一致性来让整个遍历运行完成,这是因为当集合的结构被改变的时候,fail-safe机制会在复制原集合的一份数据出来,然后在复制的那份数据遍历
java.util.concurrent包下的容器都是安全失败,可以在多线程下并发使用,并发修改。
快速失败的迭代器会抛出ConcurrentModificationException异常,而安全失败的迭代器永远不会抛出这样的异常。
缺点:
- 复制时需要额外的空间和时间上的开销。
- 因为遍历和添加操作的是不同的数组,所以不能保证遍历的是最新内容。
copyOnWritearraylist源码:
在调用add方法时Object[] newElements = Arrays.copyOf(elements, len + 1);
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
边栏推荐
- Link multiple alamofire requests - chain multiple alamofire requests
- Ar smart contact lens market prospect trends and development planning proposal report 2022-2028
- 靠,嘉立创打板又降价
- Do you know the five GoLand shortcuts to improve efficiency?
- 从零开始,如何拥有自己的博客网站【华为云至简致远】
- oss存储引出的相关内容
- Research Report on the application field of Chinese antirust oil market and the prospect planning of the 14th five year plan (2022-2028)
- Matlab learning notes (3) advanced operation of MATLAB matrix
- Analysis report on market demand trend and sales strategy of global and Chinese automatic marshmallow machines (2022-2028)
- Application of stop in screen program_ SAP LIUMENG_
猜你喜欢

打造隐私计算领先方案 冲量在线数据互联平台获得鲲鹏Validated认证

Take you to play completablefuture asynchronous programming

Institute of automation, Chinese Academy of Sciences: a review of the latest visual language pre training

webdypro layout控件不能用_SAP刘梦

Comply with medical reform and actively layout -- insight into the development of high-value medical consumables under the background of centralized purchase 2022

Rethinking atlas revolution for semantic image segmentation (deeplobv3) personal summary

Meetup review how Devops & mlops solve the machine learning dilemma in enterprises?

纽约金融监管机构发布正式的稳定币指南

消除业务代码中if....else的五种方式

What open source tools are actually used in the black cool monitoring interface?
随机推荐
Analysis report on marketing status and demand potential of China's acetate starch industry 2022-2028
Bluetooth - Bluetooth SIG
象形动态图图像化表意数据
Fiddler设置断点
防洪排涝监控 防洪排涝自动监测遥测终端
Postman parameterization
sql注入报错之注入原理实例解析
Then, we will cooperate with impulse online and Feiteng to complete partner certification and jointly create a private computing ecosystem for Xinchuang
Have you ever written a line of efficient code that equals 20 lines of others?
postman切换主题
51 timer initial value calculation
Actual combat of software testing e-commerce project (actual combat video station B has been released)
What are the pitfalls of redis's current network: using a cache and paying for disk failures?
L1-069 tire pressure monitoring (15 points)
Test question bank and simulation test for operation certificate of ordinary scaffolder (special type of construction work) in 2022
靠,嘉立创打板又降价
数字图像处理:灰度化
Fosun Group hekaiduo: grow together with Alibaba cloud and help business innovation
【BSP视频教程】BSP视频教程第17期:单片机bootloader专题,启动,跳转配置和调试下载的各种用法(2022-06-10)
Fiddler创建AutoResponder