Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Least value concurrent map

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?

like image 567
mohamed z Avatar asked Aug 21 '26 23:08

mohamed z


1 Answers

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);
    }
like image 103
Evgeniy Dorofeev Avatar answered Aug 23 '26 12:08

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!