我需要一个支持并发的映射的实现,并且只存储最少/最多的附加值(取决于比较器)。下面的代码会起作用吗?
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();
}
}
你能给我一个例子,说明它在哪里/为什么不起作用?番石榴或标准 java 库中有什么我可以使用的吗?