Add a computeIfAbsent method to the Cache

This commit is contained in:
Guillaume Nodet
2021-01-13 23:32:04 +01:00
parent 58d080484c
commit a9b69c6dee
3 changed files with 24 additions and 0 deletions

View File

@@ -16,6 +16,7 @@
package org.mvndaemon.mvnd.cache.factory;
import java.util.function.BiPredicate;
import java.util.function.Function;
/**
* Cache containing records that can be invalidated.
@@ -53,4 +54,9 @@ public interface Cache<K, V extends CacheRecord> {
*/
void removeIf(BiPredicate<K, V> predicate);
/**
* Get or compute the cached value if absent and return it.
*/
V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction);
}

View File

@@ -26,6 +26,7 @@ import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.inject.Named;
import javax.inject.Singleton;
@@ -145,5 +146,12 @@ public class TimestampCacheFactory extends AbstractLogEnabled implements CacheFa
}
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
return map.computeIfAbsent(key, k -> {
V v = mappingFunction.apply(k);
return new Record<>(v);
}).record;
}
}
}

View File

@@ -29,6 +29,7 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;
import java.util.function.Function;
import javax.inject.Named;
import javax.inject.Singleton;
import org.codehaus.plexus.logging.AbstractLogEnabled;
@@ -241,5 +242,14 @@ public class WatchServiceCacheFactory extends AbstractLogEnabled implements Cach
}
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
validateRecords();
return map.computeIfAbsent(key, k -> {
V v = mappingFunction.apply(k);
add(v);
return v;
});
}
}
}