I have this method that loads a lot of data from the database
private List<Something> loadFromDb() {
//some loading which can take a lot of time
}
I am looking for a simple way to cache the results for some fixed time (2 minutes for example). I do not need to intercept the method invocation itself, just to cache the returned data - I can write another method that does the caching if necessary.
I don't want to:
@Cacheable
in Spring - I have to define a cache for each cacheable methodIs there a library which can simplify this task, or should I do something else? An example use of such library would be
private List<Something> loadFromDbCached() {
//in java 8 'this::loadFromDb' would be possible instead of a String
return SimpleCaching.cache(this, "loadFromDb", 2, MINUTES).call();
}
EDIT: I am looking for a library that does that, managing the cache is more trouble than it seems, especially if you have concurrent access
Use Guava's Suppliers.memoizeWithExpiration(Supplier delegate, long duration, TimeUnit unit):
private final Supplier<List<Something>> cache =
Suppliers.memoizeWithExpiration(new Supplier<List<Something>>() {
public List<Something> get() {
return loadFromDb();
}
}, 2, MINUTES);
private List<Something> loadFromDbCached() {
return cache.get();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With