I am attempting to use the Google Guava Cache to cache by service related objects. On cache miss, I use my REST client to fetch the object. I know that I can do this in the following way:
CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws InternalServerException, ResourceNotFoundException {
return client.get(key);
}
};
LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader)
Now, client.getKey(Key k)
actually throws InternalServerException
and ResourceNotFoundException
. When I attempt to use this cache instance to get the object, I can catch the exception as ExecutionException
.
try {
cache.get(key);
} catch (ExecutionException e){
}
But, I would like to specifically catch and handle the exceptions that the CacheLoader I have defined is throwing(i.e. InternalServerException
and ResourceNotFoundException
).
I'm not sure if checking whether the instance of ExecutionException
is one of my own exceptions would work either, cause the signature of load() method actually throws Exception
and not ExecutionException
. Even if I could use instanceof
, it doesn't seem very clean. Are there any good appraoches for addressing this?
Values are automatically loaded by the cache, and are stored in the cache until either evicted or manually invalidated. Implementations of this interface are expected to be thread-safe, and can be safely accessed by multiple concurrent threads.
expireAfterAccess. public CacheBuilder<K,V> expireAfterAccess(long duration, TimeUnit unit) Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access.
A LoadingCache is a Cache built with an attached CacheLoader . Creating a CacheLoader is typically as easy as implementing the method V load(K key) throws Exception . So, for example, you could create a LoadingCache with the following code: [...] The canonical way to query a LoadingCache is with the method get(K) .
From javadocs:
ExecutionException - if a checked exception was thrown while loading the value. (ExecutionException is thrown even if computation was interrupted by an InterruptedException.)
UncheckedExecutionException - if an unchecked exception was thrown while loading the value
You need to check cause of caught ExecutionException by calling getCause():
} catch (ExecutionException e){
if(e.getCause() instanceof InternalServerException) {
//handle internal server error
} else if(e.getCause() instanceof ResourceNotFoundException) {
//handle resource not found
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With