frankadelic
frankadelic

Reputation: 20803

Guava LoadingCache - how to handle keys which don't exist in backing store

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?

Upvotes: 7

Views: 5837

Answers (1)

Emily
Emily

Reputation: 753

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.

Upvotes: 10

Related Questions