我需要创建一个可由多个线程访问的映射,并且只插入一个(非空)值。
为了澄清我想要做什么:
Object getValue(key)
{
if(map.get(key) != null)
return map.get(key)
else
{
Object obj = new Object();
map.put(key, obj);
return obj;
}
}
最简单的方法是使 getValue 方法同步,但我想让该方法尽可能高效,所以实际上我的要求是将“else”部分放在同步块(synchronized block)中,以某种方式锁定在“key”上' 值(value)。实现这一点的最佳方法是什么?
最佳答案
我怀疑您想要computeIfAbsent方法。
// support a map which allows concurrent access.
ConcurrentMap<Key,Value> map = ....
Value onePerKey = map.computeIfAbsent(key, Value::new);
或
Value onePerKey = map.computeIfAbsent(key, key -> new Value());
<小时/>
来自 computeIfAbsent 的 Javadoc
The default implementation is equivalent to the following steps for this map, then returning the current value or null if now absent:
if (map.get(key) == null) { V newValue = mappingFunction.apply(key); if (newValue != null) return map.putIfAbsent(key, newValue); }
The default implementation may retry these steps when multiple threads attempt updates including potentially calling the mapping function multiple times.
关于java - 实现多线程访问的java映射,每个键只更新一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604911/