Guava cache with per key expiry

16 views
Skip to first unread message

jijesh vu

unread,
May 22, 2024, 10:59:33 AMMay 22
to guava-discuss
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 ?

Jonathan Bluett-Duncan

unread,
May 28, 2024, 8:14:48 PMMay 28
to jijesh vu, guava-discuss
Hi Jijesh,

I believe the best you can do is give all keys the same expiry duration (like 30 seconds) with `expireAfterWrite`: https://github.com/google/guava/wiki/CachesExplained#timed-eviction

I hope this helps.

Cheers, 
Jonathan

On Wed, 22 May 2024, 15:59 jijesh vu, <91ji...@gmail.com> wrote:
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.

jijesh vu

unread,
May 28, 2024, 8:14:52 PMMay 28
to Jonathan Bluett-Duncan, guava-discuss
I can achieve this with the below code

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);

}


}

Reply all
Reply to author
Forward
0 new messages