当前位置:网站首页>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();
}
}
边栏推荐
- Basic use cases for jedis
- Technology sharing | quick intercom, global intercom
- PHP wechat H5 payment demo
- CAN总线协议基础
- Meetup review how Devops & mlops solve the machine learning dilemma in enterprises?
- Devops-3 cloud computing and cloud era operation and maintenance
- Desai wisdom number - words (text wall): 25 kinds of popular toys for the post-80s children
- Full array of arrays
- Pictographic dynamic graphic ideographic data
- Fiddler为测试做什么
猜你喜欢

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

Introduction to postmangrpc function

Report on development status and investment planning recommendations of global and Chinese fuel filler pipe markets (2022-2028)

Mm main tables and main fields_ SAP LIUMENG_

IDEA的Swing可视化插件JFormDesigner

隐形马尔可夫模型及其训练(一)

Why do I need a thread pool? What is pooling technology?

技术分享| 快对讲,全球对讲

Hoo Hufu Research Institute | noteworthy track in March 2022

全链路追踪 & 性能监控工具 SkyWalking 实战
随机推荐
STM32 printf garbled
Global and Chinese intelligent elderly care system industry 2 competition analysis and Investment Strategic Planning Research Report 022-2028
Pictographic dynamic graphic ideographic data
script 标签自带的属性
Quickly understand the commonly used symmetric encryption algorithm, and no longer have to worry about the interviewer's thorough inquiry
毕业季:致走向辽远未知的你
L1-069 tire pressure monitoring (15 points)
Simple file upload
CAN总线协议基础
adb不是内部或外部命令,也不是可运行的程序或批处理文件
Learn actionchains through jianshu.com and Chapter 3 of selenium webdriver
PHP wechat H5 payment demo
圆周率 π 小数点第 100 万亿数字是多少?Google 用 Debian 服务器给出了答案
卷起来,突破35岁焦虑,动画演示CPU记录函数调用过程,进互联大厂如此简单
Devops-2- from the Phoenix Project
那年高考
Only by truly finding the right way to land and practice the meta universe can we ensure the steady and long-term development
51 timer initial value calculation
Comply with medical reform and actively layout -- insight into the development of high-value medical consumables under the background of centralized purchase 2022
ASP. Net core 6 framework unveiling example demonstration [12]: advanced usage of diagnostic trace