-
How is it possible to do something like this?
I've seen examples with
How can something like this be done with the current version of Caffeine? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It is a little tougher in Caffeine because we have to balance more features and higher performance, while also trying to keep the api simple to use. The Cache<String, Connection> cache = Caffeine.newBuilder()
.expireAfter(new Expiry<String, Connection>() {
public long expireAfterCreate(String key, Connection value, long currentTime) {
return Long.MAX_VALUE;
}
public long expireAfterUpdate(String key, Connection connection,
long currentTime, long currentDuration) {
return currentDuration;
}
public long expireAfterRead(String key, Connection connection,
long currentTime, long currentDuration) {
return currentDuration;
}
}).build();
cache.policy().expireVariably().orElseThrow()
.put("connection", connection, Duration.ofMinutes(5)); For more advanced behavior where entries have different policies (some based on time-to-live, others by time-to-idle), you could wrap the value in your own class |
Beta Was this translation helpful? Give feedback.
It is a little tougher in Caffeine because we have to balance more features and higher performance, while also trying to keep the api simple to use. The
expireAfter
configures the cache to support variable expiration and thepolicy()
apis gives feature-specific methods for more advanced usages. The below examples uses a default policy where a new entry never expires if not set on creation and honors the remaining lifetime on every subsequent read or write. Theput(k, v, duration)
then create or updates the entry to set a new expiration time.