1

Is there any way to access the creation timestamp of an element from the CaffeineCache? Kind of cache.get("x").getTimestamp()?

Monta
  • 1,136
  • 1
  • 12
  • 28

2 Answers2

3

The cache tries to store the minimal metadata required to perform its operations, so some conveniences are left out to avoid waste. In those cases you should consider adding that metadata by wrapping your value.

The cache does expose runtime metadata, but this often depends on how it was constructed. That can be accessed by using Cache.policy(). For example cache.policy().expireAfterWrite() offers an ageOf(key) method to determine how long the entry has resided since its expiration timestamp was last reset. To calculate how much time until the entry expires, you could subtract the age from the policy's duration (via getExpiresAfter()).

Ben Manes
  • 9,178
  • 3
  • 35
  • 39
0

Cache interface provides getPolicy method to inspect and perform low-level operations based on the cache's runtime characteristics. For example below snippet return the age of an entry in the cache using after write policy.

private static void printAgeOfEntryUsingAfterWritePolicy(Cache cache, Object key) {
    Optional<FixedExpiration> expirationPolicy = cache.policy().expireAfterWrite();

    if (!expirationPolicy.isPresent()) {
        return;
    }

    Optional<Duration> ageOfEntry = expirationPolicy.get().ageOf(key);
    if (!ageOfEntry.isPresent()) {
        return;
    }

    Duration duration = ageOfEntry.get();

    System.out.println("Element with key " + key + " is in the cache from " + duration.getSeconds() + " seconds....");
}

Reference link.

Hari Krishna
  • 3,658
  • 1
  • 36
  • 57