Designing a Guava LoadingCache with variable entry expiry

I suggest you to include expiration time directly to your entry class and manually evict it from cache if it is expired immediately after you fetched it from cache:

MyItem item = cache.getIfPresent(key);
if (item != null && item.isExpired()) {
    cache.invalidate(key);
    item = cache.get(key);
    // or use cache.put if you load it externally
}

As an alternative, I can suggest you to check EhCache library that supports per element expire policy.


Another alternative is my ExpiringMap (I'm the author), 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);