org.infinispan.client.hotrod.near.BoundedConcurrentMapNearCache Maven / Gradle / Ivy
package org.infinispan.client.hotrod.near;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer;
import org.infinispan.client.hotrod.MetadataValue;
import org.infinispan.client.hotrod.configuration.NearCacheConfiguration;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* Near cache based on {@link BoundedConcurrentMapNearCache}
*
* @since 7.2
*/
final class BoundedConcurrentMapNearCache implements NearCache {
private final ConcurrentMap> map;
private final Cache> cache;
private BoundedConcurrentMapNearCache(Cache> cache) {
this.cache = cache;
this.map = cache.asMap();
}
public static NearCache create(final NearCacheConfiguration config,
BiConsumer super K, ? super MetadataValue> removedConsumer) {
Cache> cache = Caffeine.newBuilder()
.maximumSize(config.maxEntries())
.>removalListener((key, value, cause) -> removedConsumer.accept(key, value))
.build();
return new BoundedConcurrentMapNearCache<>(cache);
}
@Override
public boolean putIfAbsent(K key, MetadataValue value) {
return map.putIfAbsent(key, value) == null;
}
@Override
public boolean replace(K key, MetadataValue prevValue, MetadataValue newValue) {
return map.replace(key, prevValue, newValue);
}
@Override
public boolean remove(K key) {
return map.remove(key) != null;
}
@Override
public boolean remove(K key, MetadataValue value) {
return map.remove(key, value);
}
@Override
public MetadataValue get(K key) {
return map.get(key);
}
@Override
public void clear() {
map.clear();
}
@Override
public int size() {
// Make sure to clean up any evicted entries so the returned size is correct
cache.cleanUp();
return map.size();
}
@Override
public Iterator>> iterator() {
return map.entrySet().iterator();
}
}