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异常解读的更多相关文章

  1. 遍历并remove HashMap中的元素时,遇到ConcurrentModificationException

    遍历并remove HashMap中的元素时,遇到ConcurrentModificationException for (Map.Entry<ImageView, UserConcise> ...

  2. java jdk 中HashMap的源码解读

    HashMap是我们在日常写代码时最常用到的一个数据结构,它为我们提供key-value形式的数据存储.同时,它的查询,插入效率都非常高. 在之前的排序算法总结里面里,我大致学习了HashMap的实现 ...

  3. java中的ConcurrentModificationException异常

    先看这样一段代码: List<String> list = new ArrayList<String>(); list.add("1"); list.add ...

  4. 【转】ConcurrentModificationException异常解决办法 --不错

    原文网址:http://blog.sina.com.cn/s/blog_465bcfba01000ds7.html 1月30日java.util.ConcurrentModificationExcep ...

  5. 在ConcurrentModificationException异常上的联想

    1.什么是ConcurrentModificationException? 大家都听说过快速报错fast-fail吧,fast-fail的发生就是说明发生了ConcurrentModification ...

  6. 一种隐蔽性较高的Java ConcurrentModificationException异常场景

    前言 在使用Iterator遍历容器类的过程中,如果对容器的内容进行增加和删除,就会出现ConcurrentModificationException异常.该异常的分析和解决方案详见博文<Jav ...

  7. java.util.ConcurrentModificationException异常分析

    Java在操作ArrayList.HashMap.TreeMap等容器类时,遇到了java.util.ConcurrentModificationException异常.以ArrayList为例,如下 ...

  8. 集合遍历remove时ConcurrentModificationException异常

    1.集合遍历时候,有时候需要remove或add操作,这时候遍历方式可能会影响程序运行 例如: @Test public void test1() { List<Integer> intL ...

  9. Java ConcurrentModificationException异常原因和解决方法

    Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...

随机推荐

  1. HDU 5521.Meeting 最短路模板题

    Meeting Time Limit: 12000/6000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)Total ...

  2. SIFT算法

     备注:源代码还未理解,所以未附上——下周任务 一.SIFT算法 1.算法简介 尺度不变特征转换即SIFT (Scale-invariant feature transform)是一种计算机视觉的算法 ...

  3. Java程序员职业生涯规划完整版:从程序员到CTO( 摘)

    在技巧方面无论我们怎么学习,总感觉需要晋升自已不知道自己处于什么水平了.但如果有清晰的指示图供参考还是非常不错的,这样我们清楚的知道我们大概处于那个阶段和水平. Java程序员 高等特性 反射.泛型. ...

  4. clickhouse安装使用文档

    Clickhouse简介 Clickhouse是什么 1. 开源的列存储数据库管理系统 2. 支持线性扩展 3. 简单方便 4. 高可靠性 5. 容错(支持多主机异步复制,可以跨多个数据中心部署. 单 ...

  5. 关于poi导出excel三种方式HSSFWorkbook,SXSSFWorkbook,csv的总结

    poi导出excel最常用的是第一种方式HSSFWorkbook,不过这种方式数据量大的话会产生内存溢出问题,SXSSFWorkbook是一种大数据量导出格式,csv是另一种excel导出的一种轻快的 ...

  6. stm32手册上的英文

    crystal-less 无晶振 USB  FS(Full-speed)此外还有High-speed接口(简称HS),Low-speed接口(简称LS) frequency频率 CRC(Cyclic ...

  7. 转 Master-Worker模式 并行程序设计模式--Master-Worker模式

    简介 Master-Worker模式是常用的并行设计模式.它的核心思想是,系统有两个进程协议工作:Master进程和Worker进程.Master进程负责接收和分配任务,Worker进程负责处理子任务 ...

  8. git代码同步服务器代码需要注意的问题

    魔鬼藏在细节之中,git代码同步服务器代码需要注意的问题 1. 全文件夹覆盖  git pull 当前文件夹 2. 覆盖前做代码备份  mv origin origin_20190404_bak

  9. PB窗口根据分辨率的大小调整窗口大小

    //来自:http://topic.csdn.net/u/20070105/09/88f3c417-6882-4e26-b622-0f9a0a9a65e0.html //给你个通用函数,在窗口的OPE ...

  10. 【转】学习Java虚拟机没用? 听听当事人是怎么说的!

    我是大名鼎鼎的Java 虚拟机,  据说这个星球上每天有900多万程序员和我打交道,这真是一个惊人的数字. 这900多万人中不少人对我的技术内幕非常感兴趣, 有事儿没事儿都要把我“大卸八块”, 深入了 ...