当前位置:网站首页>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();
}
}
边栏推荐
- Why do I need a thread pool? What is pooling technology?
- postman常用断言
- Carry forward the past and forge ahead into the future, multiple residuals | densenet (I)
- 51 timer initial value calculation
- What is the 100th trillion digit of PI decimal point? Google gives the answer with Debian server
- Technology sharing | quick intercom, global intercom
- 消除业务代码中if....else的五种方式
- Fiddler模拟低速网络环境
- How does Dao achieve decentralized governance?
- PHP实现多张图片上传功能的示例代码
猜你喜欢

oss存储引出的相关内容

From web2 to Web3, ideology also needs to change

Embedded development: five challenges in wireless update using MCU

Pictographic dynamic graphic ideographic data

How to realize the website dark mode

postman切换主题

迪赛智慧数——文字(文本墙):80后儿童时期风靡的25种玩具

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

嵌入式开发:使用MCU进行无线更新面临的5大挑战

Devops software architecture evolution
随机推荐
Nanomq newsletter 2022-05 | release of V0.8.0, new webhook extension interface and connection authentication API
Global and Chinese intelligent elderly care system industry 2 competition analysis and Investment Strategic Planning Research Report 022-2028
Link multiple alamofire requests - chain multiple alamofire requests
NumPy 学习笔记
Exploration of kangaroo cloud data stack on spark SQL optimization based on CBO
What are the pitfalls of redis's current network: using a cache and paying for disk failures?
【Proteus仿真】DS18B20+报警温度可调+LM016显示
Fiddler设置断点
Rethinking atlas revolution for semantic image segmentation (deeplobv3) personal summary
Analysis report on marketing status and demand potential of China's acetate starch industry 2022-2028
AI video cloud: a good wife in the era of we media
PyTorch基础(一)-- Anaconda 和 PyTorch安装
How to realize the website dark mode
Analysis report on market demand trend and sales strategy of global and Chinese automatic marshmallow machines (2022-2028)
Li Ling: in six years, how did I go from open source Xiaobai to Apache top project PMC
Research Report on the application field of Chinese antirust oil market and the prospect planning of the 14th five year plan (2022-2028)
The guide to the application of all-in-one privacy computing machine - the technical requirements for financial application of all-in-one privacy computing machine was officially released to help the
Cannot locate a 64-bit Oracle Client library:The specified module could not be found.
Tactile intelligent sharing-a133 application in laryngoscope
College entrance examination that year