10

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?

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • See `RemovalListener` and it’s `RemovalCause` param. – Ben Manes Mar 07 '19 at 14:32
  • @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... – membersound Mar 07 '19 at 14:46
  • 3
    Oh. [RemovalListener](https://github.com/ben-manes/caffeine/wiki/Removal) is after while [CacheWriter](https://github.com/ben-manes/caffeine/wiki/Writer) is during. – Ben Manes Mar 07 '19 at 14:49

1 Answers1

13

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();
membersound
  • 81,582
  • 193
  • 585
  • 1,120