ConcurrentHashMap: how to replace the value of an entry only if the current value is smalle

时光毁灭记忆、已成空白 提交于 2019-12-26 06:49:28

问题


I want to:

  1. Add an entry to a ConcurrentHashMap, if there is no entry for the key, or
  2. Replace the value for the key, only if the current value is smaller.

I came up with the following code, but sine it has while (true), it looks scary to me :)

I wanted to check it with you guys. Do you think it is working?

// Input: map, k, t
while (true) {
    if (map.containsKey(k)) {
        current = map.get(k);
        if (current != null && current < t) {
            if (map.replace(k, current, t))
                break;
        } else if (current != null && current >= t) {
            break;
        }
    } else {
        pre = map.putIfAbsent(k, t);
        if (pre == null)
            break;
    }
}

回答1:


If you're using Java 8, you can use the merge method. It takes:

  • the key K to map to
  • a value V to use if there is not already a value at K
  • a BiFunction<K,K,V> F that combines any already-present value with V, and stores it at K

For your use case, you would have:

  • K: your key
  • V: the new value
  • F: a function that compares its two inputs, and returns the higher of the two

If there is not already a value at K, it'll just store V. Otherwise, it'll pass the new V and the old V to your function, and store the result at K. Since your function returns the highter of the two, this amounts to replacing the value iff it is higher than the previous value.



来源:https://stackoverflow.com/questions/38473358/concurrenthashmap-how-to-replace-the-value-of-an-entry-only-if-the-current-valu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!