объединить putIfAbsent и заменить на ConcurrentMap

У меня есть случай, когда я должен

insert a new value if the key does not exist in the ConcurrentHashMap replace the old value with a new value if the key already exists in the ConcurrentHashMap, where the new value is derived from the old value (not an expensive operation)

Я предлагаю следующий код:

<code>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);
    }
</code>

Как вы думаете, это правильно и потокобезопасно?

Есть ли более простой способ?

Ответы на вопрос(4)

Ваш ответ на вопрос