Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic cache refresh with Guava


Thanks to this forum (How to automatically refresh Cache using Google Guava?), I learn about Guava.
I wanted to ask some information about the above topic (How to automatically refresh Cache using Google Guava?) but I can't to write comments for questions because my reputation is too low. Consequently, I have to create a new topic. Thank you for your understanding.

Seeing this code,

LoadingCache<K, V> cache = CacheBuilder.newBuilder()
        .refreshAfterWrite(15, TimeUnit.MINUTES)
        .maximumSize(100)
        .build(new MyCacheLoader());

if one entry A is loaded with her value at least one time, is really the above code sufficient to reload automatically every 15 minutes the value associated to the key A ?

Of course, as mentioned by Frank, "I override the CacheBuilder.reload(K, V) method in MyCacheLoader so it performs asynchronously." Or does i have code to add ? If yes, where ? Thank you very much

PS: JB, the javadoc is perfect but my level in english is low. In fact, the overridden reload of my CacheLoader see if a real reload has to be performed for a key, and if yes, realize a real reload for that key; otherwise do not make a real reload of the cache for that key. And, even in the second case (no real reload), does I have a call of my overridden reload method every 15 minutes ? I think so but am I right ? Thanks

like image 929
Thomas Avatar asked Dec 14 '22 18:12

Thomas


1 Answers

A LoadingCache built with

LoadingCache<K, V> cache = CacheBuilder.newBuilder()
        .refreshAfterWrite(15, TimeUnit.MINUTES)
        .maximumSize(100)
        .build(new MyCacheLoader());

will not refresh automatically by itself an entry every 15 minutes, as the cache does not create threads to do any kind of management (expiring or refreshing entries). If you call cache.get(someKey) then call it again 20 minutes later, it will then refresh the entry as a consequence of your call, provided the entry has not been evicted due to the maximumSize being reached, of course.

I'm not quite sure what you're asking about CacheLoader::reload and asynchronicity. If you overrode it, you already added code, didn't you? Hopefully it's not just a call to super.reload(k, v), as that would not be asynchronous. You can complete your question with more details if needed.

However, as mentionned before, the method is not called automatically every 15 minutes for any present key, it's only called on demand when an entry is requested again.

like image 90
Frank Pavageau Avatar answered Dec 17 '22 07:12

Frank Pavageau