javacachingttlgoogle-guava-cachecache-expiration

Guava Cache expireAfterWrite is only applicable with getIfPresent used?


This question is to validate an observed behavior to ensure Guava Cache is used in correct way.

I have setup two Guava Caches (see code below): with and without a builder - as Guava documentation states:

Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort.

It appears that expiration is only observed if getIfPresent() method is used, i.e. when a key is queried then value of null is returned after a period of time > expiry interval passes upon key/value is written to the cache. In case of Cache built with CacheLoader using get() or getUnchecked() results in CacheLoader.load() method to be executed thus expiry is not observed i.e. null value is never returned.

Is this the correct expectation?

Thank you for your patience and help.

// excerpt from test code

    private static final FakeTicker fakeTicker = new FakeTicker();

    private static LoadingCache<Integer, String> usingCacheLoader = CacheBuilder.newBuilder()
                    .expireAfterWrite(2, TimeUnit.MINUTES)
                    .ticker(fakeTicker)
                    .build(new CacheLoader<Integer, String>() {
                        public String load(Integer keyName) throws Exception {
                            logger.info("Getting value for key: {}", keyName);
                            return getValue(keyName, "with_cache_loader");
                        }
                    });

    private static Cache<Integer, String> withoutCacheLoader = CacheBuilder.newBuilder()
                    .expireAfterWrite(2, TimeUnit.MINUTES)
                    .ticker(fakeTicker)
                    .build();

Solution

  • It is true that if you call get or getUnchecked you will never get null.

    The expiration can be "observed" both in terms of performance - how long it takes to get for a specific key and whether it has to be freshly computed - and in whether the actual value you get reflects perhaps out of date information.