java.util.ConcurrentModificationException 解决办法

    xiaoxiao2021-03-25  32

    在对其List<Map<String, Object>>集合进行移除的时候,报错:java.util.ConcurrentModificationException;

    List<Map<String, Object>> scheduleMaps = new ArrayList<Map<String, Object>>();

    for(Map<String, Object> m : scheduleMaps) {

    for(String k : m.keySet()) { String kString = m.get(k).toString(); if(!(kString.contains("XXX")) && ("colums".equals(k.trim()) || "columsOther".equals(k.trim()))) { m.remove(k); } }

    }

    原因和解决方法:

    使用“ConcurrentHashMap”替换HashMap,ConcurrentHashMap会自己检查修改操作,对其加锁,也可针对插入操作。 import java.util.concurrent.*;

    Map<String, Object> scheduleMap = new HashMap<String, Object>();

    改成如下:

    Map<String, Object> scheduleMap = new ConcurrentHashMap<String, Object>();

    补充:

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

    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.*;

    转载请注明原文地址: https://ju.6miu.com/read-50129.html

    最新回复(0)