HashMap中ConcurrentModificationException异常解读
HashMap是一个线程不安全的集合,如果在遍历的过程中同时对该集合进行修改操作,例如put,add,remove等,
会抛出java.util.ConcurrentModificationException异常,那么究竟这个异常为何抛出,下面从源码层面来分析一下。
跟踪代码:
查看HashMap源码,具体抛该异常的地方为:
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
如果HashMap中modCount和expectedModCount不相等,则会抛出异常
查看modCount:
具体用途是记录该HashMap修改次数,比如在对一个HashMap put操作时,会对modCount进行++modCount操作(红色标注的地方)
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
而在remove操作的时候,也会对modCount进行同样的操作:
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
查看expectedModCount:
它是HashIterator中的一个变量,在对HashMap迭代的时候,将modCount赋给expectedModCount,具体代码:
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
何时调用HashIterator():
查看HashMap entrySet()源码:
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
此处新建一个EntrySet对象,而在对EntrySet进行迭代的时候,会调用:
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
新建一个EntryIterator对象,查看该类描述:
final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
它继承HashIterator,因此在new EntryIterator()的时候会默认调用它父类HashIterator的无参构造方法。
总结:
HashMap迭代遍历的时候,会初始化expectedModCount=modCount,这时候对HashMap进行修改操作,modCount会+1,继续遍历的时候expectedModCount!=modCount,继而抛出java.util.ConcurrentModificationException异常。
HashMap中ConcurrentModificationException异常解读的更多相关文章
- 遍历并remove HashMap中的元素时,遇到ConcurrentModificationException
遍历并remove HashMap中的元素时,遇到ConcurrentModificationException for (Map.Entry<ImageView, UserConcise> ...
- java jdk 中HashMap的源码解读
HashMap是我们在日常写代码时最常用到的一个数据结构,它为我们提供key-value形式的数据存储.同时,它的查询,插入效率都非常高. 在之前的排序算法总结里面里,我大致学习了HashMap的实现 ...
- java中的ConcurrentModificationException异常
先看这样一段代码: List<String> list = new ArrayList<String>(); list.add("1"); list.add ...
- 【转】ConcurrentModificationException异常解决办法 --不错
原文网址:http://blog.sina.com.cn/s/blog_465bcfba01000ds7.html 1月30日java.util.ConcurrentModificationExcep ...
- 在ConcurrentModificationException异常上的联想
1.什么是ConcurrentModificationException? 大家都听说过快速报错fast-fail吧,fast-fail的发生就是说明发生了ConcurrentModification ...
- 一种隐蔽性较高的Java ConcurrentModificationException异常场景
前言 在使用Iterator遍历容器类的过程中,如果对容器的内容进行增加和删除,就会出现ConcurrentModificationException异常.该异常的分析和解决方案详见博文<Jav ...
- java.util.ConcurrentModificationException异常分析
Java在操作ArrayList.HashMap.TreeMap等容器类时,遇到了java.util.ConcurrentModificationException异常.以ArrayList为例,如下 ...
- 集合遍历remove时ConcurrentModificationException异常
1.集合遍历时候,有时候需要remove或add操作,这时候遍历方式可能会影响程序运行 例如: @Test public void test1() { List<Integer> intL ...
- Java ConcurrentModificationException异常原因和解决方法
Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...
随机推荐
- 杨其菊201771010134《面向对象程序设计(java)》第四周学习总结
<面向对象程序设计(java)> 第四周学习总结 第一部分:理论知识 1.类与对象 a.类(class)是构造对象的模板或蓝图.由类构造对象的过程称为创建类的实例: java中类声明的格式 ...
- PyCharm 安装package matplotlib为例
File --> settings --> Project Interpreter --> 搜索 matplotlib 如果觉得官网下载的速度慢,可以添加阿里云的 repositor ...
- shell启动执行cypher语句
1.跳转到目录:cd /data/soft/neo4j-community-not/ 2.修改配置文件:nano ./conf/neo4j.conf: 3. 登录:bin/cypher-shell - ...
- python中for循环的三种遍历方式
#!/usr/bin/env python# -*- coding: utf-8 -*-if __name__ == '__main__': list = ['A', 'B', 'C', 'D'] # ...
- ABP框架系列之三十三:(Module-System-模块系统)
Introduction ASP.NET Boilerplate provides an infrastructure to build modules and compose them to cre ...
- vue子传父多个值
子组件:this.$emit("methdosName",data1,data2,data3) 父组件: <child @methodsName="xxx(argu ...
- yesno孤立词识别kaldi脚本
path.sh主要设定路径等 export KALDI_ROOT=`pwd`/../../.. [ -f $KALDI_ROOT/tools/env.sh ] && . $KALDI_ ...
- C++中const关键字 理解
const:符号常量 使用符号常量写出的代码更容易维护:指针是边读边移动,而不是边写边移动,许多函数参数是只读不写的. const最常见用途是作为数组的界和switch分情况标号(也可以用枚举符代替 ...
- Android 发展思路
1. 做一个有 ‘特色’ 的程序员 Android 开发,本身并不是一个可以走得多远的方向,真正有价值的地方在于与具体的业务方向结合,比如:Android 与音视频技术,Android 与智能硬件交互 ...
- spring boot、cloud v2.1.0.RELEASE 使用及技术整理
2018年10月30日 springboot v2.1.0.RELEASE 发布: https://github.com/spring-projects/spring-boot/releases/ta ...