ConcurrentHashMap: how to replace the value of an

2019-09-21 03:46发布

问题:

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.



标签: java hashmap