代码示例
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());
则不再报错,执行多次不会报错,这个是什么原因呢?
你换成
System.out.println(1)
大概率也不会报错……报错是因为被其他线程修改了,正常的。
你这个例子里,println(map) 会调用 HashMap.toString(),它会遍历 EntrySet,而 EntrySet Iterator next 会检测数据变化,如果有变化就报 ConcurrentModificationException 了