Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442)
at java.util.HashMap$EntryIterator.next(HashMap.java:1476)
at java.util.HashMap$EntryIterator.next(HashMap.java:1474)
at com.alibaba.fastjson.serializer.MapSerializer.write(MapSerializer.java:108)
at com.alibaba.fastjson.serializer.MapSerializer.write(MapSerializer.java:44)
at com.alibaba.fastjson.serializer.JSONSerializer.write(JSONSerializer.java:285)
at com.alibaba.fastjson.JSON.toJSONString(JSON.java:745)
at com.alibaba.fastjson.JSON.toJSONString(JSON.java:683)
at com.alibaba.fastjson.JSON.toJSONString(JSON.java:648)
at bugReview.ConcurrentModificationExceptionReview.showException(ConcurrentModificationExceptionReview.java:33)
at bugReview.ConcurrentModificationExceptionReview.main(ConcurrentModificationExceptionReview.java:38)
出现原因: 遍历集合对象时,对该对象进行修改,就会出现该异常
问题复现:
public class ConcurrentModificationExceptionReview {
private static Map<Object, Object> request = new HashMap<>();
private static void showException() {
for (int i = 0; i < 10000; i++) {
request.put(i, i);
}
new Thread(() -> {
for (int i = 10000; i < 20000; i++) {
request.put(i,i);
for (int j = 0 ;j<10000;j++){
request.put(j,j);
// request.remove(j);
}
}
}).start();
JSON.toJSONString(request);
}
public static void main(String[] args) {
showException();
System.out.println("done");
}
}