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. 分布式协议学习笔记(三) Raft 选举自编写代码练习

    由于时间安排上的原因,这次的代码写的稍微有些简略,只能算是自己对RAFT协议的一个巩固. 实现定义2个节点,使用读取配置文件来获取IP和端口以及节点ID 网络使用boost同步流程 一个线程收 一个线 ...

  2. rabbit初学之连接测试2

    com.rabbitmq.client.ShutdownSignalException: connection error 发现,port是5672,不是15672(15672是后台管理平台的端口)

  3. (PMP)第8章-----项目质量管理

    过程质量管理,成果质量的管理 戴明理论:PDCA,戴明环 朱兰理论:质量规划,质量控制,质量改进,朱兰三部曲 克鲁斯比理论:零缺陷,质量免费 石川理论:质量圈,因果图,质量管理七大工具:核对表,帕累托 ...

  4. hdmi中深度色彩像素打包

    4个色彩像素包模式:24- 30- 36- 48- 不同模式下tmds时钟与与像素的比是位宽与24的比值 . 24 bit mode: TMDS clock = 1.0 x pixel clock ( ...

  5. 使用Jupyter Notebook编写技术文档

    1.jupyter Notebook的组成 这里它的组件及其工程构成,帮助大家更好的用好jupyter Notebook 组件 Jupyter Notebook结合了三个组件: 笔记本Web应用程序: ...

  6. 如何修改config?

    这几天在做给WCF做加密传输,结果当然是实现了加密传输,同时也发现了一个问题,有没有大神来答疑解惑一下. 事情是这样的. 在客户端的配置中,需要加入一个behavior,在config文件中是这样的. ...

  7. WPF学习笔记(6):DataSet更新后台数据库个别列失败的问题

    WPF窗体中建有一个DataGrid,运行后修改各行数据,通过Update方法更新后台数据库.发现在数据库中,其中一列FAcctID(文本型)每次都会变为0,还有一列FDebit(货币型)不能更新,其 ...

  8. linux配置防火墙和重启防火墙

    1.在linux系统里面找到并打开编辑配置防火墙的文件,执行命令: vi /etc/sysconfig/iptables. 2.在上面打开的文件里面加入一下语句: -A INPUT -m state ...

  9. HTML和CSS使用注意事项

    HTML 1.button标签 在IE中,button标签默认的type是button,而在其他浏览器和W3C标准中button默认的属性都是submit. 所以,在一个form表单中,如果butto ...

  10. Ideas

    1.蔬菜店,自带种植的菜地.(实现蔬菜都是新采摘的.) 这个试用于农村,因为需要土地.农村现在蔬菜店大多也是外出进货.有些菜放久了,就坏掉了. 这里有问题就是,(1).如果销量不够,怎么让蔬菜不烂在菜 ...