reload immediately on expiry #517
-
I am maintaining a cache of key value both are string. Each entry has its own expiry time. So I had this below working code where it reloads the data whenever any expired key is requested. As the loading of data in my case is time consuming and coming from external services, I see a need to reload the data in the background immediately whenever the expiry time passed. So when a request to get value comes after expiry, cache will be having a refreshed data already. I am using Java 8 so heard somewhere the caffeine scheduler may not work. If you have a demo and any example of how best I can achieve this with or without scheduler that would be great. Suggestions to use a different cache framework - also welcomed. My current code that expires the entry after a time but reloading happens only when the data is requested and adds up the external service call time to the get method. ` Caffeine.newBuilder().maximumSize(maxSize).recordStats().expireAfter(new Expiry<String, String>()
` |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
The Scheduler scheduler = Scheduler.forScheduledExecutorService(es);
return Caffeine.newBuilder()
.scheduler(scheduler)
.expireAfter(...)
.removalListener((key, value, cause) -> {
if (cause == RemovalCause.EXPIRED) {
load(key);
}
}).build(); In Java 9 introduced a global scheduler thread to avoid many ad hoc ones, which we expose through If you are needing to reload all expired data, then I am unsure if a bounded cache makes sense for you. A few other options to consider:
|
Beta Was this translation helpful? Give feedback.
The
Scheduler
can be used in Java 8, but you will have to supply your own thread. For example,In Java 9 introduced a global scheduler thread to avoid many ad hoc ones, which we expose through
Scheduler.systemScheduler()
. Since the 2.x release is Java 8 based, in that JVM the method falls back to returningScheduler.disabledScheduler()
. This just means you need to create and manage the lifecycle of aScheduledExecutorSe…