多线程操作HashMap异常问题

代码示例

public class MapDemo {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < 30; i++) {
            final int tmpint = i;
            new Thread(() -> {
                map.put(UUID.randomUUID().toString().substring(0, 8) + "~" + tmpint, "VALUE");
                System.out.println(map);
            }, "Thread-Name-" + i).start();
        }

        while (Thread.activeCount() > 2) {
            Thread.yield();
        }

        System.out.println(map);
        System.out.println(map.size());
    }
}

以上代码如果直接运行会报错

java.util.ConcurrentModificationException

但是如果我将代码

System.out.println(map);

给删除或者替换成

System.out.println(map.size());

则不再报错,执行多次不会报错,这个是什么原因呢?

阅读 2.8k
1 个回答

你换成 System.out.println(1)大概率也不会报错……

报错是因为被其他线程修改了,正常的。

你这个例子里,println(map) 会调用 HashMap.toString(),它会遍历 EntrySet,而 EntrySet Iterator next 会检测数据变化,如果有变化就报 ConcurrentModificationException 了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题