java ConcurrentModificationException出现原因

2021/5/17 14:55:14

本文主要是介绍java ConcurrentModificationException出现原因,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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");
    }
}


这篇关于java ConcurrentModificationException出现原因的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程