Add overloaded expireAfterWrite(), refreshAfterWrite() and expireAfterAccess() methods to CacheBuilder class
See original GitHub issueAccording to p.1 “API changes require discussion, use cases, etc. Code comes later.”, I’m going to start discussion about benefits of proposed changes.
Now com.google.common.cache.CacheBuilder contains such methods as
refreshAfterWrite(long duration, TimeUnit unit)
expireAfterWrite(long duration, TimeUnit unit)
expireAfterAccess(long duration, TimeUnit unit)
Parameters of methods listed below are used to define durations in time.
However, in Java 8 new class, java.time.Duration, was presented. It can be used to save info about time durations in exactly one object. That is easier and more transparent in some real-world scenarios.
The idea is to add overloaded methods:
refreshAfterWrite(Duration duration) expireAfterWrite(Duration duration) expireAfterAccess(Duration duration)
Proposed changes provide possibilities to simplify code:
expireAfterWrite(Duration.ofHours(3)) // instead of expireAfterWrite(3, TimeUnit.HOURS)
It makes easier to declare constant durations too:
public static final Duration EXPIRES_IN = Duration.ofHours(1); // some code after statement expireAfterWrite(EXPIRES_IN)
instead of
public static final long DURATION_LENGTH = 1; public static final TimeUnit DURATION_TIME_UNIT = TimeUnit.HOURS; // some code after statement expireAfterWrite(DURATION_LENGTH, DURATION_TIME_UNIT)
Also, it allows to execute some arifmetic operations like addition or subtraction, that can simplify program logic if multiple (and dependant) durations in different methods and/or in different caches are used. Just something like this (simplified synthetic example):
Duration expiresAfterAccessIn = Duration.ofMinutes(30); CacheBuilder.newBuilder() .expireAfterAccess(expiresAfterAccessIn) .expireAfterWrite(expiresAfterAccessIn.plusHours(1)) .build();
This improvements do not lead to changing min java sdk version and do not break existing API.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:5
- Comments:9 (9 by maintainers)
Top GitHub Comments
@kluever yes, it was a bad suggestion to use long, as it will be very easy to mess things up, so I deleted it.
Even more reason to add these overloads…I just discovered many folks inside of google writing things like:
cacheBuilder.expireAfterWrite(jodaDuration.getStandardHours(), TimeUnit.HOURS)
We’re not going to add Joda Duration overloads, but the problem here is that the API silently truncates to the hour boundary. So if
jodaDuration = Duration.standardMintues(59)
, then this expiration is set to0
!The
java.time.Duration
API is a little better, in that it makes it more explicit that you’re converting (thanks to theto
prefix), but this is still very bug prone:cacheBuilder.expireAfterWrite(javaDuration.toHours(), TimeUnit.HOURS)