近期在修程序的bug,发现后台抛出下面异常:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at com.keyman.demo.test.ClearResultTable.method2(ClearResultTable.java:54)
at com.keyman.demo.test.ClearResultTable.main(ClearResultTable.java:88)

找到报错行:at com.keyman.demo.test.ClearResultTable.method2(ClearResultTable.java:54)发现,报错位置:for (String s1 : sets)

		Set<String> sets = map.keySet();
for (String s1 : sets) {
String value = map.get(s1);
// 删除满足value以abc开头的键值对
if (value.startsWith("abc")) {
map.remove(s1);
}
}

或者以下的方式相同也会抛出异常

		Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = map.get(key);
// 删除满足value以abc开头的键值对
if (value.startsWith("abc")) {
map.remove(key);
//iterator.remove(); // 同步modCount和expectedModCount }
}

事实上无论是Map还是Set这样操作时均会抛出此异常!

解决的方法为:假设不是Iterator迭代方式,则改动map迭代方式为Iterator()方式。採用iterator.remove();而不直接通过map.remove();

                Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = map.get(key);
// 删除满足value以abc开头的键值对
if (value.startsWith("abc")) {
//map.remove(value);
iterator.remove(); // 关键代码,同步modCount和expectedModCount }
}

具体原因例如以下:

发现这个位置应该是不会报错的。查找前后文,发现最有可能报错的应该是for循环里面,可是咋一看压根没错!通过查找资料发现:当改动的个数跟期望改动的个数不相等时抛出此异常。

        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
...
final Entry<K, V> nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException(); // 抛出异常
Entry<K, V> e = current = next;
if (e == null)
throw new NoSuchElementException(); if ((next = e.next) == null) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
return e;
}
...
}

于是查看HashMap.remove()方法代码例如以下:

    /**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
} /**
* Removes and returns the entry associated with the specified key
* in the HashMap. Returns null if the HashMap contains no mapping
* for this key.
*/
final Entry<K,V> removeEntryForKey(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev; while (e != null) {
Entry<K,V> next = e.next;
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
} return e;
}

你会发现,当中有modCount++操作。modCount表示改动的次数。而并没有改变其exceptedmodCount;

接下来看看iterator.remove()方法:(java.util.Hashtable.Enumerator.remove())

	public void remove() {
if (!iterator)
throw new UnsupportedOperationException();
if (lastReturned == null)
throw new IllegalStateException("Hashtable Enumerator");
if (modCount != expectedModCount)
throw new ConcurrentModificationException(); synchronized(Hashtable.this) {
Entry[] tab = Hashtable.this.table;
int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e == lastReturned) {
modCount++;
expectedModCount++;
if (prev == null)
tab[index] = e.next;
else
prev.next = e.next;
count--;
lastReturned = null;
return;
}
}
throw new ConcurrentModificationException();
}
}
}

而此删除元素的方法,将modCount自增的同一时候将exceptedModCount相同自增。也就不会抛出异常。

java.util.ConcurrentModificationException 异常解决的方法及原理的更多相关文章

  1. java.util.ConcurrentModificationException异常原因及解决方法

    在java语言中,ArrayList是一个很常用的类,在编程中经常要对ArrayList进行删除操作,在使用remove方法对ArrayList进行删除操作时,报java.util.Concurren ...

  2. java.util.ConcurrentModificationException异常的解决

    问题复现: List<String> list = new ArrayList<>();list.add("11");list.add("55&q ...

  3. java.util.ConcurrentModificationException 异常问题详解

    环境:JDK 1.8.0_111 在Java开发过程中,使用iterator遍历集合的同时对集合进行修改就会出现java.util.ConcurrentModificationException异常, ...

  4. java.util.ConcurrentModificationException异常分析

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

  5. java.util.ConcurrentModificationException异常排查

      java.util.ConcurrentModificationException对于这个异常我们一般会认为是在遍历list的时候对这个list做了add,remove等修改操作造成的,最近在线上 ...

  6. java集合--java.util.ConcurrentModificationException异常

    ConcurrentModificationException 异常:并发修改异常,当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常.一个线程对collection集合迭代,另一个线程对Co ...

  7. Java处理java.util.ConcurrentModificationException异常

    代码: public static void reduce(HashMap<String, Integer> hashMap, final Integer count) { Iterato ...

  8. java.util.ConcurrentModificationException的解决办法

    今天在使用iterator.hasNext()操作迭代器的时候,当迭代的对象发生改变,比如插入了新数据,或者有数据被删除. 编译器报出了以下异常: Exception in thread " ...

  9. java.util.ConcurrentModificationException异常;java.util.ConcurrentModificationException实战

    写代码遇到这个问题,很多博客文章都是在反复的强调理论,而没有对应的实例,所以这里从实例出发,后研究理论: 一.错误产生情况 1 .字符型 (1)添加 public static void main(S ...

随机推荐

  1. 86.express里面的app.configure作用

    以下摘自 express 3.0 的 文档 app.configure([env], callback) Conditionally invoke callback when env matches ...

  2. zookeeper的理解与概述

    文章转自https://www.cnblogs.com/likehua/p/3999600.html  感谢博主 文章转自:http://www.aboutyun.com/thread-9266-1- ...

  3. [BZOJ3884] 上帝与集合的正确用法 (欧拉函数)

    题目链接:  https://www.lydsy.com/JudgeOnline/problem.php?id=3884 题目大意: 给出 M, 求 $2^{2^{2^{2^{...}}}}$ % M ...

  4. [CQOI2009] 叶子的颜色 解题报告(树形DP)

    题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1304 Description 给一棵m个结点的无根树,你可以选择一个度数大于1的结点作为 ...

  5. OpenGL编程逐步深入(九)插值处理

    注:文中VS代指顶点着色器,FS代指片段着色器. 准备知识 这个教程和大家展示3d管道中非常重要的部分,即Interpolation(插值).光栅化程序执行的插值变量由VS产生.正如你已经见到过的,为 ...

  6. LINUX 上源代码安装与配置samba服务,支持从windows上读写LINUX文件。

    ###动机###在windows编写代码文件比较方便,因为有source insight.但是需要在LINUX上编译.一种办法就是使用samba文件共享. [1] 下载samba代码.按照config ...

  7. vue-router路由配置

    转自http://www.cnblogs.com/padding1015/ 两种配置方法:在main.js中 || 在src/router文件夹下的index.js中 src/router/index ...

  8. apache(XAMPP)禁止IP访问的httpd-vhosts.conf设置

    httpd-vhosts.conf <virtualhost *:80> ServerName 123.123.123.123   ServerAlias 123.123.123.123  ...

  9. 【CS Round #36 (Div. 2 only) A】Bicycle Rental

    [题目链接]:https://csacademy.com/contest/round-36/task/bicycle-rental/ [题意] 让你从n辆车中选一辆车; 每一辆车有3个属性 1.到达车 ...

  10. rman数据库恢复;关键/非重要文件、影像副本、控制文件、还原点、非归档、增量、新数据库、灾难性回复

    运行全然恢复:在 ARCHIVELOG 模式下 丢失了系统重要数据文件: 假设某个数据文件丢失或损坏.且该文件属于 SYSTEM 或 UNDO 表空间,请运行下面步骤: 1. 实例可能会也可能不会自己 ...