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 ...
随机推荐
- python 06函数
python中函数定义方法: def test(x): "The function definitions" x+=1 return x def:定义函数的关键字test:函数名( ...
- .NET Core 中使用GB2312编码报错的问题
错误描述 环境 dotnet 2.1.4 现象 当代码中使用 System.Text.Encoding.GetEncoding("GB2312") //或者 System.Text ...
- w9 Ansible批量管理与维护
Ansible是2013年推出的一种通用自动化工具,可用于配置管理或工作流程自动化.配置管理是一种“基础架构代码”实践,它将事物编码,例如应该在系统上安装什么包和版本,或者应该运行什么守护进程.工作流 ...
- JAVA 8 主要新特性 ----------------(一)总纲
一.版本中数据结构的修改浅析 二.JDK1.8优点概括 三.新功能Lambda表达式入门 四.Lambda函数式接口 五.Lambda方法引用与构造器引用 六.集合Stream API 七.新时间日期 ...
- TensorFlow基本--张量
在TensorFlow中所有的数据都通过张量的形式表示,从功能上看张量可以被简单的理解为多维数据,其中零阶张量表示标量(一个数),第一阶张量为向量(一个一维数组),第n阶向量可以理解为一个n维数组. ...
- python3 与 Django 连接数据库报错:ImportError: No module named 'MySQLdb'
在 python2 中,使用 pip install mysql-python 进行安装连接MySQL的库,使用时 import MySQLdb 进行使用 在 python3 中,改变了连接库,改为了 ...
- handoop安装部署集群
hdfs 1.0版本 一个namenode (secordary namenode 2.0冷备份) 和多个datanode构成分布式文件系统 mapreduce 一个 jobtracker 协调 ta ...
- 【repost】javascript:;与javascript:void(0)使用介绍
有时候我们在编写js过程中,需要触发事件而不需要返回值,那么就可能需要这样的写法 最近看了好几个关于<a>标签和javascript:void(0)的帖子,谨记于此,以资查阅. 注:以下代 ...
- 32 bit 与 64 bit 程序(1)如何识别?
一, 怎样判断一个exe可执行程序是32位的还是64位的? 简单的方法: 一般来说在64位的windows7下,打开任务管理器可以知道哪些程序是32位的哪些是64位的,但是因为自己的电脑是64位的wi ...
- Autofac与AOP功能例子
using Autofac.Extras.DynamicProxy; using System; using System.Collections.Generic; using System.Linq ...