Guava 18.0.
I am trying to work out the refreshAfterWrite
with the following code, I think
return the **key on load**
after 3 seconds
return update the key to uppercase (automatically)
this is the loader
ExecutorService executor = Executors.newCachedThreadPool();
mockLoader = new CacheLoader<String, String>() {
//return key
@Override
public String load(String key) throws Exception {
System.out.println("loaindg.....");
return key;
}
// load-behind. asyn loading.
@Override
public ListenableFuture<String> reload(final String key, String result) {
ListenableFutureTask<String> task = ListenableFutureTask.create(new Callable<String>() {
public String call() {
System.out.println("reloaindg.....");
return key.toUpperCase();
}
});
executor.execute(task);
return task;
}
};
}
and this is the cache
cache.setRefreshAfterWrite(3);
cache.setCacehLoader(mockLoader);
but in the test, the reload didnot happen as expected.
String key = "a";
String firstGet = cache.get(key);
assertTrue(key.equals(firstGet));
sleep(refrehTime + 3);
// I must use the get to trigger the reload
String secondGet = cache.get(key);
assertTrue(key.toUpperCase().equals(secondGet));
is this correct?
is that possible to trigger the reload automatically?
This is due to performing the refresh asynchronously on an executor, which allows the read to be non-blocking and return the stale value. If you use a
MoreExecutors.directExecutor()
then the test will pass. Also note that you can useFakeTicker
to manipulate time instead of sleeping. Alternatively you may prefer to use expiration instead of refresh.