gpt4 book ai didi

java - 最小值并发映射

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:29:33 26 4
gpt4 key购买 nike

我需要一个 map 的实现,支持并发,并且只存储最少/最多的附加值(取决于比较器)。以下代码是否有效?

 class LeastValConcurrentMap<K, V> {

//put the least value
private final Comparator<V> comparator;
private final ConcurrentHashMap<K, V> map = new ConcurrentHashMap<K, V>();

LeastValConcurrentMap(Comparator comparator) {
this.comparator = comparator;
}

public void put(K k, V v) {
V vOld = map.put(k, v);
if (vOld == null || comparator.compare(v, vOld) <= 0) //i.e. v <= vOld so better
return;
//recursively call self
put(k, vOld);
}

@Override
public String toString() {
return map.toString();
}
}

能否请您举例说明它在哪里/为什么不起作用?guava 或标准 java 库中有什么我可以使用的吗?

最佳答案

我觉得比较复杂,需要用atomic ConcurrentHashMap.replace(K key, V oldValue, V newValue)

public void put(K k, V v) {
V oldValue = map.putIfAbsent(k, v);
if (oldValue == null) {
// this is the first mapping to this key
return;
}
for (;;) {
if (comparator.compare(v, oldValue) <= 0) {
break;
}
// this replace returns true only if oldValue was replaced with new value atomically
if (map.replace(k, oldValue, v)) {
break;
}
// otherwise another attempt
oldValue = map.get(k);
}

关于java - 最小值并发映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com