Java 缓存库 mapdb 到期最大大小

Java cache library mapdb expire max size

我想使用 mapdb 库来缓存最大 n 个对象。我写了这样的东西:

DB dbMemory = DBMaker
              .memoryDB()
              .make();

HTreeMap<Long, String> inMemory = dbMemory
              .hashMap("inMemory", Serializer.LONG, Serializer.STRING)
              .expireMaxSize(2)
              .create();

inMemory.put((long)1, "1");
inMemory.put((long)2, "2");
inMemory.put((long)3, "3");
inMemory.put((long)4, "4");

inMemory.getValues().forEach(val -> System.out.println(val));

我的预期结果应该是:

3
4

但我得到了(并不总是按这个顺序):

1
2
3
4

我确信这只是我对使用这个库的误解所以有人可以告诉我我做错了什么吗?

HTreeMap documentation 说:

Time based eviction will always place entry into Expiration Queue. But other expiration criteria (size and space limit) also needs hint when to place entry into Expiration Queue. In following example no entry is placed into queue and no entry ever expires.

HTreeMap cache = db
    .hashMap("cache")
    .expireMaxSize(1000)
    .create();

所以你需要添加一个提示。文件进一步说:

There are three possible triggers which will place entry into Expiration Queue: expireAfterCreate(), expireAfterUpdate() and expireAfterGet().

添加这些 - 您可能需要创建和更新提示。