javacachingmapdb

Java cache library mapdb expire max size


I'd like to use mapdb library to cache max n object. I wrote something like this:

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));

My expected result should be just:

3
4

But I got (not always in this order):

1
2
3
4

I am sure that it just my misunderstanding of using this library so could someone show me what I am doing wrong?


Solution

  • The HTreeMap documentation says:

    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();
    

    So you need to add a hint. The documentation further says:

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

    Add those - you probably want the create and update hints.