ConcurrentHashMap:只有在当前值较小的情况下如何替换条目的值 [英] ConcurrentHashMap: how to replace the value of an entry only if the current value is smalle

查看:168
本文介绍了ConcurrentHashMap:只有在当前值较小的情况下如何替换条目的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想:


  1. 如果没有密钥条目,或者
  2. 添加条目到ConcurrentHashMap
  3. 只有在当前值较小时才替换该键的值。

我想出了下面的代码,但正弦它有(真),它看起来可怕的我:)

我想与你们检查一下。你认为它是有效的吗?

  //输入: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;
}
}


解决方案

您正在使用Java 8,您可以使用 merge 方法。它需要:


  • 要映射的键K

  • 要使用的值V还不是K的值

  • a BiFunction< K,K,V> F将任何已经存在的值与V相结合,并将其存储在K



对于您的使用情况,您可以:


  • K:您的密钥

  • V:新值

  • F:比较两个输入的函数,返回两个较高的值



如果在K处没有值,它只会存储V.否则,它会通过新的V和将旧的V存储到函数中,并将结果存储在K中。由于函数返回两者中较高的值,因此如果它高于先前值,则相当于替换该值。


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;
    }
}

解决方案

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.

这篇关于ConcurrentHashMap:只有在当前值较小的情况下如何替换条目的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆