I want to:
- Add an entry to a ConcurrentHashMap, if there is no entry for the key, or
- 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;
}
}
If you're using Java 8, you can use the
merge
method. It takes:BiFunction<K,K,V>
F that combines any already-present value with V, and stores it at KFor your use case, you would have:
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.