Collections.synchronized 映射是否使迭代器线程安全

Tou*_*one 5 java dictionary iterator synchronized concurrentmodification

一个系统中有两个线程。一个是读者线程,另一个是作者线程。

使用以下代码同步地图。

Map<String,ArrayList<String>> m = Collections.synchronizedMap(new HashMap<String,ArrayList<String>())
Run Code Online (Sandbox Code Playgroud)

读取器线程获取映射值的迭代器,同时写入器线程修改映射。

所以,我的问题是 Iterator 会抛出ConcurrentModificationException吗?

zap*_*apl 3

或许。这样做并不安全。文档说

当迭代任何集合视图时,用户必须在返回的映射上手动同步

Collections.synchronized...使单个方法调用原子化,因此它们不需要进一步的同步。但迭代不仅仅是单个方法调用,因此它需要额外的同步。下面是一个例子

    Map<String, String> shared = Collections.synchronizedMap(new HashMap<>());

    new Thread(() -> {
        while (true) {
            synchronized (shared) {
                for (String key : shared.keySet()) {
                    System.out.println(key);
                }
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                break;
            }
        }
    }).start();

    new Thread(() -> {
        while (true) {
            try {
                // this is atomic
                shared.put(UUID.randomUUID().toString(), "Yo!");
                Thread.sleep(1000);
            } catch (Exception e) {
                break;
            }
        }
    }).start();
}
Run Code Online (Sandbox Code Playgroud)