ComputeIfAbsent equivalent in Java 7

Is there a way to run a piece of code only if the key does not exist in ConcurrentHashMapand save the result of the code in the collection?

I cannot use Java 8 features because I am developing for Android.

Also, I would like to avoid doing long operations if I don’t need it, and I don’t want to destroy the atomic operation of the collection to do this.

+7
source share
2 answers

There is no exact equivalent, but the usual approach looks something like this:

ConcurrentMap<Key,Value> map = ...

Value computeIfAbsent(Key k) {
  Value v = map.get(k);
  if (v == null) {
    Value vNew = new Value(...); // or whatever else you do to compute the value
    v = (v = map.putIfAbsent(k, vNew)) == null ? vNew : v;
  }
  return v;
}

computeIfAbsent Java 8, , Value - . - - Value , Value *, .

, , , get() putIfAbsent. , , computeIfAbsent , . 5 , , .

, ( , , ), Guava CacheBuilder LoadingCache. , , Java 8 CHM, .

+8

. - .

-1

Source: https://habr.com/ru/post/1660821/


All Articles