当前位置: 移动技术网 > IT编程>开发语言>Java > 出现java.util.ConcurrentModificationException 问题及解决办法

出现java.util.ConcurrentModificationException 问题及解决办法

2019年07月22日  | 移动技术网IT编程  | 我要评论

java.util.concurrentmodificationexception 解决办法

前言:

在使用iterator.hasnext()操作迭代器的时候,如果此时迭代的对象发生改变,比如插入了新数据,或者有数据被删除。

则使用会报以下异常:

java.util.concurrentmodificationexception
    at java.util.hashmap$hashiterator.nextentry(hashmap.java:793)
    at java.util.hashmap$keyiterator.next(hashmap.java:828)

例如以下程序(转自互联网):

mport java.util.*; 
 
public class main 
{ 
public static void main(string args[]) 
{ 
main main = new main(); 
main.test(); 
} 
 
public void test() 
{ 
map bb = new hashmap(); 
bb.put("1", "wj"); 
bb.put("2", "ry"); 
iterator it = bb.keyset().iterator(); 
while(it.hasnext()) { 
object ele = it.next(); 
      bb.remove(ele);  //wrong 
} 
system.out.println("success!"); 
} 
} 

原因:iterator做遍历的时候,hashmap被修改(bb.remove(ele), size-1),iterator(object ele=it.next())会检查hashmap的size,size发生变化,抛出错误concurrentmodificationexception。

解决办法:

1) 通过iterator修改hashtable

while(it.hasnext()) {
object ele = it.next();
      it.remove();
}

2) 根据实际程序,您自己手动给iterator遍历的那段程序加锁,给修改hashmap的那段程序加锁。

3) 使用“concurrenthashmap”替换hashmap,concurrenthashmap会自己检查修改操作,对其加锁,也可针对插入操作。

import java.util.concurrent.*;

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网