Guava LoadCache - how to handle keys that do not exist in the backup storage

I use CacheBuilder and LoadingCache to implement a cache in a database in data memory.

Suppose a client requests a cache for an item that does not exist in the backup storage. I want the client to know that no data was found for the specified key. What is the best approach for this?

  • Store a special value in the cache, which means "no data".
  • Do not cache anything or throw an exception.
  • Other ideas?
+6
source share
1 answer

I always solved it as follows.

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 should change the interface for KeyValueService to always return optional, but sometimes this is not possible.

You can use weighting to quickly remove all optional links. ABSENT.

+9
source

Source: https://habr.com/ru/post/917992/


All Articles