跟进这个问题(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/