Designing a Guava LoadingCache with variable entry expiry

fge picture fge · Dec 20, 2012 · Viewed 12k times · Source

I am using Guava's LoadingCache into my project to handle thread-{safe,friendly} cache loading and it works wonderfully well. However, there is a limitation.

The current code defining the cache looks like this:

cache = CacheBuilder.newBuilder().maximumSize(100L).build(new CacheLoader<K, V>()
{
    // load() method implemented here
}

I don't specify an expiry time.

The problem is that according to the values of the key, some associated values may expire and others may not. And CacheLoader does not account for this, if you specify an expiry time, it is for each and every entry.

How would you tackle this problem?

Answer

Jonathan picture Jonathan · Dec 16, 2014

Another alternative is ExpiringMap, which supports variable entry expiration:

Map<String, String> map = ExpiringMap.builder().variableExpiration().build();
map.put("foo", "bar", ExpirationPolicy.ACCESSED, 5, TimeUnit.MINUTES);
map.put("baz", "pez", ExpirationPolicy.CREATED, 10, TimeUnit.MINUTES);