Is there a CacheEntryExpiredListener for Caffeine Cache?
Asked Answered
N

1

12

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?

Nestorius answered 7/3, 2019 at 14:17 Comment(3)
See RemovalListener and it’s RemovalCause param.Gorky
@BenManes is the remove listener called before or after the entry is removed from cache? I'm asking because I want to write the expired entries into a database. And want to make sure I'm not having a state where an entry is not present in the caffeine anymore, but also not yet persisted...Nestorius
Oh. RemovalListener is after while CacheWriter is during.Gorky
N
14

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();
Nestorius answered 7/3, 2019 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.