org.infinispan.hotrod.near.BoundedConcurrentMapNearCache Maven / Gradle / Ivy
The newest version!
package org.infinispan.hotrod.near;
import java.util.Iterator;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
import org.infinispan.api.common.CacheEntry;
import org.infinispan.hotrod.configuration.NearCache;
import org.infinispan.hotrod.configuration.NearCacheConfiguration;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* Near cache based on {@link BoundedConcurrentMapNearCache}
*
* @since 14.0
*/
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,
Consumer super CacheEntry> removedConsumer) {
Cache> cache = Caffeine.newBuilder()
.maximumSize(config.maxEntries())
.removalListener((key, value, cause) -> removedConsumer.accept(null))
.build();
return new BoundedConcurrentMapNearCache<>(cache);
}
@Override
public boolean putIfAbsent(K key, CacheEntry entry) {
return map.putIfAbsent(key, entry) == null;
}
@Override
public boolean replace(K key, CacheEntry prevValue, CacheEntry newValue) {
return map.replace(key, prevValue, newValue);
}
@Override
public boolean remove(K key) {
return map.remove(key) != null;
}
@Override
public boolean remove(K key, CacheEntry entry) {
return map.remove(key, entry);
}
@Override
public CacheEntry 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.values().stream().iterator();
}
}