Reputation: 2812
Could somebody explain me please how to use the Guava CacheBuilder correctly.
Should getFromNetwork() raise an exception or return null, if the data is not reachable? Should I raise the Execution Exception and use guavaCache.get(). I am just not sure what the documentation means with unchecked exceptions?
Do I use the CacheBuilder as is it supposed to be used? I dont use guavaCache.put()? this is done automatically. right?
guavaCache = CacheBuilder.newBuilder()
.maximumSize(maxCapacity)
.expireAfterWrite(1, TimeUnit.HOURS)
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {}
})
.build(
new CacheLoader<String, byte[]>() {
public byte[] load(String key) throws Exception {
return getFromNetwork(key);
}
});
private byte[] get(Object... params) {
String url = paramsToUri(params).toString();
byte[] data = null;
data = guavaCache.get(url); //?
data = guavaCache.getUnchecked(url); //?
return data;
}
Upvotes: 1
Views: 1011
Reputation: 140328
I think the Javadoc for load
is quite clear:
Returns:
the value associated with key; must not be null
Throws:
Exception - if unable to load the result
If the data is not reachable, you are unable to load the result, so throw an Exception.
Do I use the CacheBuilder as is it supposed to be used? I dont use guavaCache.put()? this is done automatically. right?
Yes, this looks fine to me, although you only need to call one of get
or getUnchecked
. You definitely don't need to put
.
Upvotes: 3