guava缓存api中的RemovalListener回调无法正常工作

时间:2013-09-30 11:13:32

标签: java caching guava

我使用guava缓存支持编写以下代码来测试缓存过期。 在下面的代码我创建一个缓存,从密钥11000到30000添加20个条目,经过一些睡眠遍历存在缓存中的密钥并搜索两个密钥(19000和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;
 }

}

在主要方法上面运行后,我看到以下结果

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

我有3个问题

  1. 为什么其他关键类似17000,19000,25000未通知 RemovalListener
  2. 缓存时缓存键集上的迭代为空的原因 大小是12
  3. 为什么在缓存大小时搜索19000和29000为空 是12

2 个答案:

答案 0 :(得分:3)

直接来自Javadocs:

  

如果请求expireAfterWrite或expireAfterAccess,则可能会在每次缓存修改,偶尔的缓存访问或对Cache.cleanUp()的调用时逐出条目。过期的条目可能由Cache.size()计数,但读取或写入操作永远不可见。

Guava的缓存不会在到期时间后立即清理条目;这是因为它(故意)不会为缓存维护创建额外的线程。在各种查询操作中经常执行清理。特别是,上述文档解释了size()方法可能会临时计算过期条目。

答案 1 :(得分:0)

此外,对于那些花费数小时试图找出第一个问题答案的人(比如我):

在内部创建并发级别大于1的guava缓存会创建固定数量的哈希表段,并将条目分配给任何创建的哈希表段。当条目存在的哈希表段发生缓存访问/写入时,RemovalListener仅会收到这些条目的通知。