Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching the result of a method in java [closed]

Tags:

java

caching

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:

  • Use AOP compile time weaving like this one - it requires changes in the build
  • Use @Cacheable in Spring - I have to define a cache for each cacheable method

Is 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

like image 592
jmruc Avatar asked Nov 29 '22 15:11

jmruc


1 Answers

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();
}
like image 121
thSoft Avatar answered Dec 04 '22 03:12

thSoft