1

I want to implement a cache using Guava's caching mechanism.

I have a DB query which returns a map, I want to cache the entire map but let it expire after a certain amount of time.

I realize Guava caches works as a per-item bases. We provide a key, the Cache will either returns the corresponding value from the cache or get it.

Is there a way to use Guava to get everything, cache it but timeout it after a certain time period of time and get everything again.

Many thanks

3
  • 1
    LoadingCache is probably what you need. See also this question: stackoverflow.com/questions/11463675/… Commented Sep 24, 2013 at 15:42
  • It almost sounds like you want a Cache<Singleton, Map<Key, Value>>, with just a single key. Commented Sep 24, 2013 at 16:44
  • Cache.asMap().putAll(yourMap) could be a solution if you need to cache items in your map. Commented Sep 24, 2013 at 21:41

1 Answer 1

2

You can create an instance of Supplier<Map<K,V>> that fetches the entire map from the database, and then use Suppliers.memoizeWithExpiration to cache it.

Related:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.