java - Collections.synchronized 映射是否使 Iterator 线程安全

标签 java dictionary iterator synchronized concurrentmodification

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

使用以下代码同步 map 。

Map<String,ArrayList<String>> m = Collections.synchronizedMap(new HashMap<String,ArrayList<String>())

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

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

最佳答案

也许吧。这样做不安全。 documentation

It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views

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

关于java - Collections.synchronized 映射是否使 Iterator 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33190500/

相关文章:

java - 'registerCustomer()' 应该属于客户类还是主/驱动程序类

python - 使用 Dictionary get 方法返回空列表默认​​返回 None

javascript - 将数组动态映射到嵌套对象

python - itertools 或手写生成器 - 哪个更好?

rust - 类型不匹配错误 : expected `char` , 找到引用

java - 在 Java 中减去时间字符串

java - 按多列对 JFace TableViewer 进行排序

java - 运行 JJWT Json token 时出现运行时或类错误

python - 如何在 Python 中将嵌套列表转换为字典,其中 lst[0][0] 是键

c++ - 使用 STL 的迭代器上的 UTF-8 到 UTF-32