本文介绍了组合putIfAbsent并替换为ConcurrentMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个usecase,我必须

I have a usecase where I have to


  • 如果ConcurrentHashMap中不存在该键,则插入一个新值

  • 如果
    中的键已经存在,则使用新值替换旧值ConcurrentHashMap,其中新值从旧值派生(不是昂贵的操作)

我有以下代码:

public void insertOrReplace(String key, String value) {
        boolean updated = false;
        do {
            String oldValue = concurrentMap.get(key);
            if (oldValue == null) {
                oldValue = concurrentMap.putIfAbsent(key, value);
                if (oldValue == null) {
                    updated = true;
                }
            }
            if (oldValue != null) {
                final String newValue = recalculateNewValue(oldValue, value);
                updated = concurrentMap.replace(key, oldValue, newValue);
            }
        } while (!updated);
    }

你认为这是正确的和线程安全的吗?

Do you think it's correct and thread-safe?

有更简单的方法吗?

推荐答案

下面是相当于你的。我已经压力测试了一些与成千上万的线程并发访问它:它的工作原理,与一些重试(循环)执行(显然,你永远不能证明正确性在并发世界中的测试)。

You could make it a little shorter with the code below which is equivalent to yours. I have stress tested it a little with thousands of threads accessing it concurrently: it works as expected, with a number of retries (loops) being performed (obviously, you can never prove correctness with testing in the concurrent world).

public void insertOrReplace(String key, String value) {
    for (;;) {
        String oldValue = concurrentMap.putIfAbsent(key, value);
        if (oldValue == null)
            return;

        final String newValue = recalculateNewValue(oldValue, value);
        if (concurrentMap.replace(key, oldValue, newValue))
            return;
    }
}

这篇关于组合putIfAbsent并替换为ConcurrentMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:18