将 putIfAbsent 合并为 ConcurrentMap 替换
2022-09-02 22:10:28
						我有一个用例,我必须
- 如果 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);
    }
你认为它是正确的和线程安全的吗?
有没有更简单的方法?