Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ConcurrentMap不一致性_Java - Fatal编程技术网

Java ConcurrentMap不一致性

Java ConcurrentMap不一致性,java,Java,ConcurrentMap-putIfAbsent的JavaDoc说: /** * If the specified key is not already associated * with a value, associate it with the given value. * This is equivalent to * * if (!map.containsKey(key)) * return map.put(key, val

ConcurrentMap-putIfAbsent的JavaDoc说:

  /**
    * If the specified key is not already associated
    * with a value, associate it with the given value.
    * This is equivalent to
    *
    * if (!map.containsKey(key))
    *     return map.put(key, value);
    * else
    *    return map.get(key);
    *  
    * except that the action is performed atomically.
    */  

但是putIfAbsent(来自ConcurrentMap)和put(来自Map)都返回上一个值(如果没有上一个值,则返回null)。因此,在本例中,当映射不包含键时,返回null。这是代码的正确意图吗?返回“value”不是更好吗?

最有可能的是,API是这样设计的,这样您就可以区分以前没有映射(并且更新成功)和以前存在映射但映射到完全相同的
值的情况

问一下这是否比获得新值更实际是无济于事的。我有时也会偶然发现这种行为。但是这个API是从Java5开始的,它是以这种方式指定的,并且不会被更改


作为补充说明,如果之前没有映射存在,Java8将返回计算值,其行为将更像您预期的那样。

您已经(或者应该)有了新值。没有理由返回刚才插入的内容

    ConcurrentMap<Integer, String> map = new ConcurrentHashMap<>();
    ...
    String newVal = "someString";
    String old = map.putIfAbsent(1, newVal);
    if(old == null){
        //no previous mapping
    }
ConcurrentMap=new ConcurrentHashMap();
...
String newVal=“someString”;
字符串old=map.putIfAbsent(1,newVal);
if(old==null){
//没有以前的映射
}

您已经有了value。谢谢,我只是想显示if(!map.containsKey(key))返回map.put(key,value);always returns falseMap.ComputeFabSent非常好,因为您总是移交一个函数,它只在必要时执行昂贵的操作。没错,
Map.ComputeFabSent
是自第一个版本的
ConcurrentMap
以来我所错过的…