Sunday, 4 November 2012

Guava light cache

If you have a need to declare a small cache which have to be cleared periodically you can easily do it using Guava Cache.
We have to define loader that will load cache element and a period after which it will throw an item away. And then next read will use a loader to load an element into cache again. We can also define a cache in the way it will throw away an item if it was not read for a period of time.
Here is an example:
private LoadingCache<String, MyClass> cache;
CacheLoader<String, MyClass> loader = new CacheLoader<String, MyClass> () {
      public MyClass load(String key) throws Exception {
        return ourService.get(key);
cache = CacheBuilder.newBuilder().
        expireAfterWrite(1, TimeUnit.MINUTES).

More about this subject here:

No comments: