RemovalListener callback in guava caching api does not work correctly
I write following codes for test cache expiretion with using guava caching
support. in following code i create a cache, add 20 entry to it from key
11000 to 30000, after some sleep traverse exist keies in cache and search
for two key (19000 and 29000)
import com.google.common.cache.*;
import java.util.concurrent.TimeUnit;
public class TestGuavaCache {
public static int evictCount = 0;
public static void main(String[] args) throws InterruptedException {
Cache<Integer, Record> myCache = CacheBuilder.newBuilder()
.expireAfterAccess(10, TimeUnit.SECONDS)
.expireAfterWrite(15, TimeUnit.SECONDS)
.concurrencyLevel(4)
.maximumSize(100)
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object>
notification) {
evictCount++;
System.out.println(evictCount + "th removed key >> " +
notification.getKey()
+ " with cause " + notification.getCause());
}
})
.recordStats()
.build();
int nextKey = 10000;
for (int i = 0; i < 20; i++) {
nextKey = nextKey + 1000;
myCache.put(nextKey, new Record(nextKey, i + " >> " + nextKey));
Thread.sleep(1000);
}
System.out.println("=============================");
System.out.println("now go to sleep for 20 second");
Thread.sleep(20000);
System.out.println("myCache.size() = " + myCache.size());
for (Integer key : myCache.asMap().keySet()) {
System.out.println("next exist key in cache is" + key);
}
System.out.println("search for key " + 19000 + " : " +
myCache.getIfPresent(19000));
System.out.println("search for key " + 29000 + " : " +
myCache.getIfPresent(29000));
}
}
class Record {
int key;
String value;
Record(int key, String value) {
this.key = key;
this.value = value;
}
}
After running above main method i see following result
1th removed key >> 11000 with cause EXPIRED
2th removed key >> 13000 with cause EXPIRED
3th removed key >> 12000 with cause EXPIRED
4th removed key >> 15000 with cause EXPIRED
5th removed key >> 14000 with cause EXPIRED
6th removed key >> 16000 with cause EXPIRED
7th removed key >> 18000 with cause EXPIRED
8th removed key >> 20000 with cause EXPIRED
=============================
now go to sleep for 20 second
myCache.size() = 12
search for key 19000 : null
search for key 29000 : null
I have 3 Question
why others key similar 17000,19000,25000 does not notified in RemovalListener
why iteration on cache keyset is empty while cache size is 12
why search for 19000 and 29000 is null while cache size is 12
No comments:
Post a Comment