Guava 18.0 refreshAfterWrite

257 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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 use FakeTicker to manipulate time instead of sleeping. Alternatively you may prefer to use expiration instead of refresh.

Expiration and refresh are closely related but different mechanisms. An expired entry is considered stale and cannot be used, so it must be discarded and refetched. An entry eligible for being refreshed means that the content is still valid to use, but the data should be refetched as it may be out of date. Guava provides these TTL policies under the names expireAfterWrite and refreshAfterWrite, which may be used together if the refresh time is smaller than the expiration time.

Answer to scalacache memoization asynchronous refresh