Search code examples
javaspring-bootguava

JAVA Guava cache refresh existing elements


I am using Guava to handle caching in my web application; I want to auto refresh the existing elements in my cache every 10 minutes.

this is my snippet code:

private Cache<String, Integer> cache = CacheBuilder.newBuilder.build();

//my main method
public Integer load(String key){
    Integer value = cache.getIfPresent(key)
    if(value == null){
        value = getKeyFromServer(key);
        //insert in my cache
        cache.put(key, value);
    }
    return value;
}

I want to enhance the above code in order to refresh the elements gathered in my cache map as bellow:

 //1. iterate over cache map
 for(e in cache){
    //2. get new element value from the server
    value = getKeyFromServer(e.getKey());
    //3. update the cache
    cache.put(key, value);
 }

Solution

  • You have to use Guava Cache a bit more. There is no need to call getIfPresent or put as the mechanism is handled automatically.

    LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
           .expireAfterWrite(10, TimeUnit.MINUTES)
           .build(
               new CacheLoader<String, Integer>() {
                 @Override
                 public Integer load(Key key) throws Exception {
                   return getKeyFromServer(key);
                 }
               });
    

    Source: https://github.com/google/guava/wiki/CachesExplained

    Please note that Guava Cache is deprecated in Spring 5: https://stackoverflow.com/a/44218055/8230378 (you labeled the question with spring-boot).