← 中文资源

简体中文版本

遍历 Map 时 put 的两种命运

在遍历 HashMap 的同时 put 属于结构性修改,下一次 next() 就抛 ConcurrentModificationException;ConcurrentHashMap 弱一致遍历不抛异常,但不保证看到新写入的键。

阅读英文原文

实现说明

遍历 Map 时 put 的两种命运以类 MapPutDuringIteration和函数 main为骨架。 for (String key : scores.keySet()) 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 直接运行文件,输出会带上标签,比如 HashMap failed:、ConcurrentHashMap iterated without exception、size after =——输出的每一行都能指回产生它的那次调用。

常见问题

运行「遍历 Map 时 put 的两种命运」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 HashMap failed:、ConcurrentHashMap iterated without exception、size after = 这类标签。

核心语句

Map<String, Integer> concurrent = new ConcurrentHashMap<>();
Map<String, Integer> scores = new HashMap<>();
concurrent.put("a", 1);

代码示例

import java.util.HashMap;
import java.util.Map;
import java.util.ConcurrentModificationException;
import java.util.concurrent.ConcurrentHashMap;

public class MapPutDuringIteration {

    public static void main(String[] args) {
        // HashMap:遍历途中 put 属于结构性修改,下一次 next() 即抛 CME
        Map<String, Integer> scores = new HashMap<>();
        scores.put("a", 1);
        scores.put("b", 2);
        try {
            for (String key : scores.keySet()) {
                scores.put("c", 3);
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("HashMap failed: " + e.getClass().getSimpleName());
        }

        // ConcurrentHashMap:弱一致遍历,边写边遍历不抛异常
        // 但不保证遍历能看到迭代开始后写入的键
        Map<String, Integer> concurrent = new ConcurrentHashMap<>();
        concurrent.put("a", 1);
        concurrent.put("b", 2);
        for (String key : concurrent.keySet()) {
            concurrent.put("c", 3);
        }
        System.out.println("ConcurrentHashMap iterated without exception");
        System.out.println("size after = " + concurrent.size());
    }
}