1

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?

ip.java
  • 83
  • 11
Kapitalny
  • 651
  • 2
  • 8
  • 17

1 Answers1

13

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));
Ben Manes
  • 9,178
  • 3
  • 35
  • 39
  • i saw sample like this in Caffeine examples and did not get it fully. And I'm at bit lazy now to check sources. So, when entry is checked for expiration it checks it current lifetime and compares it with expireAfterCreate, that is why this examples works (and works only for creation). So, after it expired for the first time would it be ok or would it be expired no matter updated we or not? In other words, should we redefine all three methods? – Alexo Po. Nov 02 '21 at 22:53
  • btw, you are the author of Caffeine -). Maybe this Expiry example should be written a bit more about in examples. Here is detailed answer to same question: https://stackoverflow.com/a/64310026/5027938 – Alexo Po. Nov 02 '21 at 23:02
  • 1
    @AlexoPo. That answer was good. The returned durations is the cutoff for when the entry is invalid and cannot be retrieved from the cache. That timestamp is stored to validate on retrieval and for internal ordering to quickly discard expired entries. Since the cache uses only O(1) algorithms there is no scans with re-evaluations. It also only retains a single timestamp, so an update calculates a new lifetime (here indicating no change). – Ben Manes Nov 03 '21 at 00:12
  • 1
    @AlexoPo. Maybe we need tutorials to provide more depth and examples. A user's guide is a terse overview. As the author it is difficult to write from the user's perspective and to know what they need. What's nice is that some people have written blog posts or SO answers to share what confused them and the solution, like what you linked to. I haven't written tutorials as I'm afraid the best authors are users and I'd happy accept those contributions to the project. – Ben Manes Nov 03 '21 at 00:14