如果未写入密钥,我已经创建了一个基于 Guava CacheBuilder 的缓存,其有效期为 5 秒。添加了一个removingListener 来打印被移除的键/值对。我观察到的是侦听器的 onRemoval 方法仅在第一次被调用。第二次删除条目时不会调用它。(实际的删除发生了。只是没有调用removingListener 的onRemoval 方法)。
难道我做错了什么?有人可以帮忙吗?提前致谢。这是我的代码:
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
public class TestCacheBuilder {
public static void main(String[] args) {
try {
new TestCacheBuilder();
}catch (Exception e){
e.printStackTrace();
}
}
public TestCacheBuilder() {
Cache<String, String> myCache = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.SECONDS)
.removalListener(new RemovalListener<String, String>() {
public void onRemoval(RemovalNotification<String, String> removal) {
System.out.println("removal: "+removal.getKey()+"/"+removal.getValue());
}
})
.build();
Map<String, String> inMap = myCache.asMap();
inMap.put("MyKey", "FirstValue");
System.out.println("Initial Insert: "+inMap);
//Wait 16 seconds
try {
Thread.sleep(4000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("After 4 seconds: " + inMap);
inMap.put("MyKey", "SecondValue");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("After 1 more second: " + inMap);
try {
Thread.sleep(4000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("After 4 more seconds: " + inMap);
}
}
输出如下:
Initial Insert: {MyKey=FirstValue}
After 4 seconds: {MyKey=FirstValue}
removal: MyKey/FirstValue
After 1 more second: {MyKey=SecondValue}
After 4 more seconds: {}