当前位置:网站首页>Fail fast and fail safe
Fail fast and fail safe
2022-06-10 17:00:00 【Zhangzhiming (hard work version)】
fail-fast( Fast failure )
When we're traversing the set elements , Iterators are often used , But in the process of iterators traversing elements , If the structure of the set is changed , Will throw an exception , Prevent further traversal . This is the so-called fast failure mechanism . namely : Once the traversal is found, others will modify Throw the exception immediately .java.util All collection classes below the package fail quickly
We can iterate through list,Iterator It's an interface , ArrayList Internal class implementation Iterator Interface to implement related methods The code is as follows among expectedModCount It records the initial use of Iterator Ergodic time ArrayList Modified several times If there is 4 Elements Then it is modified 4 Time expectedModCount=4; Calling next() When the method moves to the next element Must be called first checkForComodification() Inspection ; modCount != expectedModCount These two values are equal at first All are 4 -->int expectedModCount = modCount;
If the iterator is traversing the element , If modCount This value has changed , Then an exception will be thrown when traversing again . When we change the number of elements in the set ,modCount The value of will be changed , If you remove , Insert . But modification will not .
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 ( Security failure )
When we make changes to the set structure , To adopt fail-safe In terms of mechanism , Does not throw an exception . namely : Find someone else to modify while traversing There should be coping strategies For example, sacrificing consistency to make the whole traversal run complete , This is because when the structure of the set is changed ,fail-safe The mechanism will copy a piece of data from the original set , Then traverse the copied data
java.util.concurrent The containers under the package are all security failures , It can be used concurrently in multithreading , Concurrent modification .
A fast failing iterator throws ConcurrentModificationException abnormal , The iterator of security failure will never throw such an exception .
shortcoming :
- Replication requires extra space and time overhead .
- Because the traversal and addition operations are different arrays , So there is no guarantee that you will be traversing the latest content .
copyOnWritearraylist Source code :
Calling add When the method is used 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();
}
}
边栏推荐
- 创建 Visual Studio 离线安装包并安装
- Desai wisdom number - words (text wall): 25 kinds of popular toys for the post-80s children
- Postman common assertions
- Flood control and drainage monitoring automatic monitoring and telemetering terminal for flood control and drainage
- 提升园区服务水平,优化营商环境该从哪些方面入手
- Basic settings of pycharm [detailed explanation with pictures and words]
- Then, we will cooperate with impulse online and Feiteng to complete partner certification and jointly create a private computing ecosystem for Xinchuang
- PHP实现多张图片上传功能的示例代码
- 全链路追踪 & 性能监控工具 SkyWalking 实战
- Cannot locate a 64-bit Oracle Client library:The specified module could not be found.
猜你喜欢

Embedded development: five challenges in wireless update using MCU

China coal machinery industry development research and investment prospect analysis report 2022-2028 Edition

Do you know the five GoLand shortcuts to improve efficiency?

postman切换主题

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

接口测试学习笔记

How to realize the website dark mode

This paper introduces three feature selection methods in machine learning

adb不是内部或外部命令,也不是可运行的程序或批处理文件

What open source tools are actually used in the black cool monitoring interface?
随机推荐
Cannot locate a 64-bit Oracle Client library:The specified module could not be found.
VBA divides strings, stores them in an array, writes them to a file, and saves them
【BSP视频教程】BSP视频教程第17期:单片机bootloader专题,启动,跳转配置和调试下载的各种用法(2022-06-10)
Full array of arrays
为 Chocolatey 设置代理
webdypro layout控件不能用_SAP刘梦
mysql数据库实现设置字段长度
Do you know the five GoLand shortcuts to improve efficiency?
隐形马尔可夫模型及其训练(一)
Comply with medical reform and actively layout -- insight into the development of high-value medical consumables under the background of centralized purchase 2022
From web2 to Web3, ideology also needs to change
智慧景区视频监控 5G智慧灯杆网关组网综合杆
Institute of automation, Chinese Academy of Sciences: a review of the latest visual language pre training
Fabric.js 激活输入框
CAN总线协议基础
只有真正找到落地和实践元宇宙的正确方式,才能保证发展的行稳致远
技术分享| 快对讲,全球对讲
postman参数化
嵌入式开发:使用MCU进行无线更新面临的5大挑战
How does Dao achieve decentralized governance?