【发布时间】:2013-08-21 14:36:01
【问题描述】:
如果使用 ConcurrentHashMap 作为映射,我会问自己实现线程安全的正确方法是什么?
在一本书中我发现了这样的内容:
private ConcurrentHashMap<KEY, VALUE> cache = new ConcurrentHashMap<>();
public V put(KEY key, VALUE value) {
VALUE ret = cache.get(key);
if (ret == null) {
ret = cache.putIfAbsent(key, value);
if (ret == null) {
ret = value;
}
}
return ret;
}
现在我问自己是否有必要像这样使 get 和可能的 put 原子化:
public V put(KEY key, VALUE value) {
synchronized(cache) {
VALUE ret = cache.get(key);
if (ret == null) {
ret = cache.putIfAbsent(key, value);
if (ret == null) {
ret = value;
}
}
}
return ret;
}
因为当 cache.get() 返回 null 时,另一个线程可能会使第一个线程的 cache.get() 结果无效?
干杯 奥利弗
【问题讨论】:
-
那么你的问题到底是什么?
-
我的问题是是否有必要将调用 cache.get(...) 和 cache.putIfAbsent(...) 放在同步块中并使用缓存监视器。
-
不,没有必要。
putIfAbsent为您处理原子性(正如它在 javadoc 中所述)。
标签: java caching thread-safety concurrenthashmap