Guava LoadingCache - how to handle keys which don't exist in backing store
caching, guava, java
Solution
I've always solved this in the following way.
interface KeyValueService<K,V> {
V get(K key);
}
class CachingKeyValueService<K,V> {
Cache<K,Optional<V>> cache;
V get(K key) {
return cache.get(key).orNull();
}
}
Ideally you would change the interface for KeyValueService to always return Optional, but sometimes thats not possible.
You can use weighting to cause all Optional.ABSENT references to be evicted quickly.
Problem
I am using CacheBuilder and LoadingCache to implement an in-memory cache of database data. Suppose a client queries the cache for an item that does not exist in the backing store. I want the client to know that no data was found for the specified key. What is the best approach for handling this? - Store special value in cache which signifies "no data". - Store nothing in cache and raise exception. - Other ideas?