相关疑难解决方法(0)

Java 8 Map中putIfAbsent和computeIfAbsent有什么区别?

阅读一篇有趣的文章,这些人声称这两个功能的区别在于:

如果Map中没有指定的Key,则两个函数都希望添加元素.

putIfAbsent添加具有指定Value的元素,而computeIfAbsent添加具有使用Key计算的值的元素. http://www.buggybread.com/2014/10/java-8-difference-between-map.html

我们已经看到putIfAbsent删除了必须定义if语句的必要方法,但是如果获取Java文章真的会损害我们的性能呢?

为了优化这一点,我们不想在我们确定需要它们之前获取文章 - 这意味着在获取文章之前我们需要知道密钥是否缺失. http://www.deadcoderising.com/2017-02-14-java-8-declarative-ways-of-modifying-a-map-using-compute-merge-and-replace/

我还没准备好了解哪些差异可以请你详细说明这两个功能?

java java-8

53
推荐指数
4
解决办法
3万
查看次数

如何解决findbug对java.util.concurrent.ConcurrentHashMap的调用序列可能不是原子的

嗨我得到的错误"调用java.util.concurrent.ConcurrentHashMap的序列可能不是原子的"当我在我的项目中运行find bug时,代码如下.

public static final ConcurrentHashMap<String,Vector<Person>> personTypeMap = new ConcurrentHashMap<String, Vector<Person>>();

    private static void setDefaultPersonGroup() {


        PersonDao crud = PersonDao.getInstance();
        List<Person> personDBList = crud.retrieveAll();
        for (Person person : personDBList) {
            Vector<Person> personTypeCollection = personTypeMap.get(person
                    .getGroupId());
            if (personTypeCollection == null) {
                personTypeCollection = new Vector<Person>();
                personTypeMap.put(personTypeCollection.getGroupId(),
                        personTypeCollection);
            }
            personTypeCollection.add(person);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我在线下的personTypeMap.put(personTypeCollection.getGroupId(),personTypeCollection)面临问题;

任何人都可以帮我解决问题.

java findbugs concurrenthashmap java.util.concurrent

9
推荐指数
1
解决办法
4218
查看次数

如何以computeIfAbsent效率实现Map putIfAbsent语义?

考虑以下代码:

ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>();

boolean foo(String key) {
    Value value = map.get(key);
    if (value == null) {
        value = map.putIfAbsent(key, new Value());
        if (value == null) {
            // do some stuff
            return true;
        }
    }
    // do some other stuff
    return false;
 }
    
Run Code Online (Sandbox Code Playgroud)

假设foo()由多个线程并发调用。还假设呼叫new Value()是昂贵的。代码很冗长,仍然会导致Value创建冗余对象。上述逻辑能否以一种保证不Value创建冗余对象的方式实现(即new Value()最多调用一次)?我正在寻找一个干净的实现 - 最少的代码而不显式获取锁。

computeIfAbsent 可能是一个不错的选择,但是它的返回语义不符合所需的逻辑。

java

6
推荐指数
1
解决办法
289
查看次数