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

Kevin
  • 5,972
  • 17
  • 63
  • 87
  • 1
    `LoadingCache` is probably what you need. See also this question: http://stackoverflow.com/questions/11463675/how-to-automatically-refresh-cache-using-google-guava?rq=1 –  Sep 24 '13 at 15:42
  • It almost sounds like you want a `Cache>`, with just a single key. – Louis Wasserman Sep 24 '13 at 16:44
  • Cache.asMap().putAll(yourMap) could be a solution if you need to cache items in your map. – Andrey Chaschev Sep 24 '13 at 21:41

1 Answers1

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:

Community
  • 1
  • 1
David
  • 2,947
  • 1
  • 25
  • 19