modCount的作用
来源:互联网 发布:linux中sed命令详解 编辑:程序博客网 时间:2024/06/16 19:48
在ArrayList,LinkedList,HashMap等等的内部实现增,删,改中我们总能看到modCount的身影,modCount字面意思就是修改次数,但为什么要记录modCount的修改次数
以HashMap为例
private abstract class HashIterator<E> implements Iterator<E> { Entry<K,V> next; // next entry to return int expectedModCount; // For fast-fail int index; // current slot Entry<K,V> current; // current entry HashIterator() { expectedModCount = modCount; if (size > 0) { // advance to first entry Entry[] t = table; while (index < t.length && (next = t[index++]) == null) ; } } public final boolean hasNext() { return next != null; } final Entry<K,V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); Entry<K,V> e = next; if (e == null) throw new NoSuchElementException(); if ((next = e.next) == null) { Entry[] t = table; while (index < t.length && (next = t[index++]) == null) ; } current = e; return e; } public void remove() { if (current == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); Object k = current.key; current = null; HashMap.this.removeEntryForKey(k); expectedModCount = modCount; } }
由以上代码可以看出,在一个迭代器初始的时候会赋予它调用这个迭代器的对象的mCount,如何在迭代器遍历的过程中,一旦发现这个对象的mcount和迭代器中存储的mcount不一样那就抛异常
好的,下面是这个的完整解释
Fail-Fast 机制
我们知道 java.util.HashMap 不是线程安全的,因此如果在使用迭代器的过程中有其他线程修改了map,那么将抛出ConcurrentModificationException,这就是所谓fail-fast策略。这一策略在源码中的实现是通过 modCount 域,modCount 顾名思义就是修改次数,对HashMap 内容的修改都将增加这个值,那么在迭代器初始化过程中会将这个值赋给迭代器的 expectedModCount。在迭代过程中,判断 modCount 跟 expectedModCount 是否相等,如果不相等就表示已经有其他线程修改了 Map:注意到 modCount 声明为 volatile,保证线程之间修改的可见性。
所以在这里和大家建议,当大家遍历那些非线程安全的数据结构时,尽量使用迭代器
阅读全文
0 0
- modCount的作用
- Arraylist中的modCount 的作用
- 容器中的modCount作用
- modCount
- for循环遍历删除数据的异常及modCount的作用
- modCount到底是干什么的呢
- modCount到底是干什么的呢
- modCount到底是干什么的呢
- Arraylist源码中modCount的位置
- arraylist等记录修改次数modCount有什么作用?
- expectedModCount和modCount关系,以及concurrentHashMap不加读锁的原因
- Java ArrayList(AbstractList)之 modCount++ 此字段属性的英文注释翻译。
- Arraylist中的modCount
- ArrayList中的modCount与ConcurrentModificationException
- 作用域::的作用
- 作用域的作用
- ::的作用
- !!的作用
- C语言对图片进行base64编码
- 关于VERIFY_OCTAL_PERMISSIONS权限检查
- 观察者模式应用在Gridview、Adapter原理解析
- linux学习---常用时间函数
- 区间相交问题
- modCount的作用
- PDF转HTML常用方法分享
- 微信小程序开发遇到的坑
- 15.linux内存管理概括
- 记一次安卓适配的解决
- Spring 2.5配置文件详解
- spark将数据写入hbase以及从hbase读取数据
- JAVA中常见的四种排序--冒泡排序、选择排序、插入排序和快速排序 详解
- c语言 母串和子串的匹配问题