Search code examples
javacaffeine-cache

How do I make invalidate an entry and return its value from a Caffeine Cache?


I'm trying to remove an entry from the Caffeine cache manually. I have two attempts but I suspect that there are some problems with both of them:

This one seems like it could suffer from a race condition.

cache.get(key);
cache.invalidate(key);

This one seems to be bypassing the methods of the cache itself so I'm not sure if there are strange side effects that result.

cache.asMap().remove(key);

Is there a standard way to do this or a method of the cache that I'm missing here?


Solution

  • You should use cache.asMap().remove(key) as you suspected. The other call delegates to this, but does not return the value because that is not idiomatic for a cache.

    The Cache interface is opinionated for how one should commonly use a cache, while the asMap() view is more raw to allow for advanced operations. For example, you generally wouldn't iterate over a cache (e.g. memcached doesn't allow this), but if you need to then the Map provides that support. All calls flow into the same backing structure, so there will be no inconsistency. The APIs merely try to nudge users towards best practices, but strive to not block a developer from getting their work done safely and correctly.