I require an implementation of a map, that supports concurrency, and only stores the least/most value added (depending on the comparator). Would the following code work?
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();
}
}
Can you please give me an example of where/why it wouldn't work? Is there something in the guava or standard java library I could use?
I think it is more complex, you need to use 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With