Search code examples
cachingguavagoogle-guava-cache

How to skip / avoid some specific elements to be cached by Guava Cache


Is there a way to not cache some specific elements using Guava Cache? I still want the element to be returned, but not cached.

For example:

LoadingCache guavaCache;

public Element load(String key) {
  Element element = requestElement(key);

  if(element.isActive == false){
    guavaCache.dontCache(element);
  }

  return element;
}

Solution

  • I implemented a solution for this problem: invalidate the element after return it. This will removed the element from the cache right after inserted it.

    Cache config:

    public Element load(String key) {
      return requestElement(key);
    }
    

    then:

    element = guavaCache.get(key);
    if(element.isActive == false){
      guavaCache.invalidate(key)
    }
    

    This seems not very clean but it's being done internally by Guava.