java - 实现多线程访问的java映射,每个键只更新一次

标签 java dictionary concurrency

我需要创建一个可由多个线程访问的映射,并且只插入一个(非空)值。

为了澄清我想要做什么:

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/

相关文章:

java - FutureTasks 和 CachedThreadPool 是如何工作的

sql-server - 在更新语句中递增时是否存在并发问题

java - 如何验证 hibernate validator 上的所有组?

java - Surefire 2.18v 带有 testng、mave 和 selenium webdriver

java - 似乎无法让 Lombok 在单元测试中工作

python - 将 pandas Dataframe 列映射到字典值

java - jackson 不会下课

Python 将元组列表转换为嵌套字典列表

android - Scrollable ImageView Android 问题(过度滚动)

java - javax.swing.plaf.nimbus.ImageCache 中 ReentrantReadWriteLock 的用法