java.util.ConcurrentModificationException异常解决方法

java.util.ConcurrentModificationException异常(转)
1、

今天在写一个带缓存功能的访问代理程序时出现了java.util.ConcurrentModificationException异常, 因为该异常是非捕获型异常而且很少见,所以费了些时间才找到问题所在,原来在通过Iterator进行遍历的时候,如果直接对HashMap进行操作后,再继续用之前的Iterator进行遍历就会出现这个异常,表示其HashMap已经被修改。

源程序代码片段如下:caches为一个HashMap对象

 String sameKeyPart = accesserClassName + "@" + methodName + "@" + parameterKeyString + "@";
 Iterator keys = caches.keySet().iterator();
 String key = null;
 while (keys.hasNext()) ...{
   key = (String) keys.next();
   if (key.startsWith(sameKeyPart)) ...{
     caches.remove(key);
   }
 }

解决办法为通过其相应的Iterator进行删除就可以了,修改后代码片段如下:

 String sameKeyPart = accesserClassName + "@" + methodName + "@" + parameterKeyString + "@";
 Iterator keys = caches.keySet().iterator();
 String key = null;
 while (keys.hasNext()) ...{
   key = (String) keys.next();
   if (key.startsWith(sameKeyPart)) ...{
     keys.remove();
   }
 }

http://blog.sina.com.cn/s/blog_465bcfba01000ds7.html

你可能感兴趣的:(笔记,java)