I know Cache2k
having a CacheEntryExpiredListener
that is only triggered if a cache entry self-expires (not when being invalidated explicit).
Cache<String, Object> cache = Cache2kBuilder.of(String.class, Object.class)
.addListener(
(CacheEntryExpiredListener<String, Object>) (cache, entry)
-> handleExpired(entry.getKey(), entry.getValue()))
.expireAfterWrite(60, TimeUnit.SECONDS)
.build();
Question: how could I achieve the same using caffeine
cache implementation?
Thanks to the hint from @Ben Manes:
Caffeine.newBuilder()
.removalListener((key, value, cause) -> {
if (cause.wasEvicted()) System.out.printf("key=%s, value=%s", key, value);
})
.expireAfterWrite(60, TimeUnit.SECONDS)
.build();