javacachingcaffeine

Caffeine - how expires Cached values only after creation time


Caffeine has expiresAfterWrite method which looks at last write time. I want it to look only at the creation time. So when the first entry comes then entry will be expired after a fixed amount of time without looking at the number of updates on this entry. Is this possible?


Solution

  • Yes, but requires using the more advanced Expiry api. In the below example, a newly created entry has a fixed 5 minute lifetime. This is done by returning currentDuration on an update or read.

    LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
        .expireAfter(new Expiry<Key, Graph>() {
          public long expireAfterCreate(Key key, Graph graph, long currentTime) {
            return TimeUnit.MINUTES.toNanos(5);
          }
          public long expireAfterUpdate(Key key, Graph graph, 
              long currentTime, long currentDuration) {
            return currentDuration;
          }
          public long expireAfterRead(Key key, Graph graph,
              long currentTime, long currentDuration) {
            return currentDuration;
          }
        })
        .build(key -> createExpensiveGraph(key));