Example of Caffeine per key expiryusage

1.2k Views Asked by At

Are there any examples of how to use per key expiry in Caffeine?

I see the following example -- does it mean we are create a Caffeine cache instance per key?

https://github.com/ben-manes/caffeine/issues/114#issuecomment-300602200

Caffeine.newBuilder()
.expireAfter(new Expiry<Key, Graph>() {
  public long expireAfterCreate(Key key, Graph graph, long currentTime) {
    return (graph instanceof NullGraph)
        ? TimeUnit.MINUTES.toNanos(1)
        : TimeUnit.MINUTES.toNanos(10);
  }
  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));

I looked at the implementation and see how the implementation of the expiry interface is used internally.

So say my graph object had a method for expiry duration .. would this be a correct usage?

final Cache<Key, Graph> cache = Caffeine.newBuilder()
.expireAfter(new Expiry<Key, Graph>() {
  public long expireAfterCreate(Key key, Graph graph, long currentTime) {
    return currentTime + graph.expireAfterNanos();
  }
  public long expireAfterUpdate(Key key, Graph graph, 
      long currentTime, long currentDuration) {
    return Long.Max;
  }
  public long expireAfterRead(Key key, Graph graph,
      long currentTime, long currentDuration) {
    return Long.Max;
  }
})
.build();

Now any time I do something like the following -- per key expiry will be enabled for the key inserted -

cache.put(key, graph); // key and graph creation not shown here.
0

There are 0 best solutions below