Skip to content

Instantly share code, notes, and snippets.

@kijanowski
Created September 30, 2019 16:04
Show Gist options
  • Save kijanowski/3e051a481c4c44b83802a078735daefd to your computer and use it in GitHub Desktop.
Save kijanowski/3e051a481c4c44b83802a078735daefd to your computer and use it in GitHub Desktop.
public class CustomGuavaBasedCache<U, V> implements CacheMap<U, V> {
private static final Logger LOG = LoggerFactory.getLogger(CustomGuavaBasedCache.class);
private Cache<U, V> cache;
public CustomGuavaBasedCache(long maxCacheSize, long expiryInSeconds) {
this.cache = CacheBuilder
.newBuilder()
.maximumSize(maxCacheSize)
.expireAfterWrite(expiryInSeconds, TimeUnit.SECONDS)
.removalListener(notification -> LOG.info("Key {} got removed, because: {}", notification.getKey(), notification.getCause()))
.build();
}
@Override
public boolean containsKey(U key) {
return cache.getIfPresent(key) != null;
}
@Override
public V get(U key) {
return cache.getIfPresent(key);
}
@Override
public CacheMap<U, V> set(U key, V value) {
cache.put(key, value);
return this;
}
@Override
public CacheMap<U, V> delete(U key) {
cache.invalidate(key);
return this;
}
@Override
public CacheMap<U, V> clear() {
cache.invalidateAll();
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment