I have following spring cache config:
spring.cache.guava.spec: expireAfterWrite=1s
Then I have test for it:
@Test
public void test_not_work() {
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
expect("real method called TWO times");
// because cache should be expired after 1s
// It DOESN'T work, real method only called once
}
@Test
public void test_works() {
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
sleep(2s);
callCachedMethod(..);
expect("real method called THREE times");
// because cache should be expired after 1s
// IT WORKS!!
}
can someone explain it?
It's because Guava does not ensure the eviction of the values automatically when the timeout value expires.
Per its documentation here:
Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort. Instead, it performs small amounts of maintenance during write operations, or during occasional read operations if writes are rare.