Is there any option for guava cache to behave like each key with expiry time. When the key reached its age can be removed and fetch new values from api ?
--
guava-...@googlegroups.com
Project site: https://github.com/google/guava
This group: http://groups.google.com/group/guava-discuss
This list is for general discussion.
To report an issue: https://github.com/google/guava/issues/new
To get help: http://stackoverflow.com/questions/ask?tags=guava
---
You received this message because you are subscribed to the Google Groups "guava-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to guava-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/guava-discuss/e58c15b5-2c6f-478d-b5bc-98ed69b23268n%40googlegroups.com.
public class PerKeyExpirationCache<k, v>
{
private final Cache<k, v> cache;
private final Map<k, Long> expirationTimes;
public PerKeyExpirationCache()
{
this.cache = CacheBuilder.newBuilder().build();
this.expirationTimes = new ConcurrentHashMap<>();
}
public void put(k key, v value, long duration, TimeUnit unit)
{
cache.put(key, value);
expirationTimes.put(key, System.nanoTime() + unit.toNanos(duration));
}
public v get(k key) throws ExecutionException
{
if (isExpired(key)) {
cache.invalidate(key);
expirationTimes.remove(key);
}
return cache.getIfPresent(key);
}
private boolean isExpired(k key)
{
return expirationTimes.containsKey(key) && System.nanoTime() > expirationTimes.get(key);
}
public void invalidate(k key)
{
cache.invalidate(key);
expirationTimes.remove(key);
}
}