You can check if the value is null with the getIfPresent command.
if the value is null then you can submit a task which loads values asynchronously and continue with your flow.
example :
Map<String, String> map = cache.getIfPresent(key);
if(map == null){
executorService.submit(new Callable<Map<String, String>>() {
@Override
public Map<String, String> call() throws Exception {
return cache.get(key);
}
});
}
else{
continue with the flow...
}
you should also use the refreshAfterWrite feature and implement the reload method if you want to refresh the values in the cache while you are still reading the old value.
In this ways the cache will be always updated and the main thread that read the values won't be affected.
example :
cache = CacheBuilder.newBuilder()
.refreshAfterWrite(30, TimeUnit.SECONDS)
.build(
new CacheLoader<String, Map<String,String>>() {
public Map<String, String> load(String key) throws Exception {
map = hardWork(key)//get map from from DB -- expensive time commend
return map;
}
@Override
public ListenableFuture<Map<String, String>> reload(final String key, Map<String, String> oldValue) throws Exception {
// we need to load new values asynchronously, so that calls to read values from the cache don't block
ListenableFuture<Map<String, String>> listenableFuture = executorService.submit(new Callable<Map<String, String>>() {
@Override
public Map<String, String> call() throws Exception {
//Async reload event
return load(key);
}
});
return listenableFuture;
}
});