Java CHM 同步

标签 java multithreading concurrenthashmap

跟进这个问题(Java thread safety - multiple atomic operations?),我不想再添加更多的问题,但现在我有这个疑问:

private final Map<String, Set<String>> data = Maps.newConcurrentMap();

... then in a method ...

if (data.containsKey("A")) {
    data.get("A").add("B");
}

应该是这样的:

synchronized(data) {
    if (data.containsKey("A")) {
        data.get("A").add("B");
    }
}

为了线程安全。对吗?

所以操作是原子的,但是组合它们需要同步,对吗?到那时,只使用一个简单的 HashMap 而不是并发 HashMap 是否有意义,因为我们要手动处理同步?

CHM 中是否有任何方法可以自动完成这项工作?

最佳答案

在您的特定情况下,您可能希望使用 computeIfPresent method ConcurrentHashMap:

data.computeIfPresent("A", (k, v) -> { v.add("B"); return v; } );

来自 javadocs:

If the value for the specified key is present, attempts to compute a new mapping given the key and its current mapped value. The entire method invocation is performed atomically.

因此不需要显式同步。

关于Java CHM 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41625992/

相关文章:

java - JDBC sql查询(批处理)

c - Pthread程序计数器

java - ConcurrentHashMap 锁定

java - 理解 ConcurrentHashMap 计算方法的代码

java - 同时用于不同数据库的 jooq-codegen-maven 插件

java - 如何序列化一个包含 ObservableList 的对象?

javascript - 无法从不同的 WebApp (Tomcat) 获取图像/JS

java - java.util.Vector 序列化线程安全吗?

python - 使用pyqtgraph使用外部数据进行绘图

java - ConcurrentHashMap 中位移运算符的使用