1

I have a method annotated with @Cacheable. If an exception is captured inside the method, I want the cache to be cleared. However, it seems that the cache is loaded in an aspect that is executed after the line that clears it. Therefore, when an Exception is captured in the method, even though the cache is cleared, the empty string result stays in the cache.

Where should I clear the cache from?

@Cacheable("myCache") 
public String myMethod() {
    String result="";
    try {
        result = doSomething();
    } catch (Exception e) {
        cacheManager.getCache("myCache").clear();
    }
    return token;
}
6
  • Have you considered using @CacheEvict ?
    – Mr R
    Mar 10, 2021 at 11:44
  • @MrR actually I'm using it. But from where should I call the method annotated with @CacheEvict?
    – Andres
    Mar 10, 2021 at 12:12
  • Not having looked at the Spring code I would guess that Spring wraps calls to myMethod with some code that drops the return value into the cache (because of the annotation). If you catch the exception and still return something it has no way of knowing that the cache shouldn't be updated - so perhaps you should propogate the exception (at least 1 layer further out [again I would summize that no caching is going to happen in the exceptional case - what value does it have to cache? If you want myCache cleared - I'd still do whatever you need for that too].
    – Mr R
    Mar 10, 2021 at 12:28
  • Ok, but I would prefer not to propagate the Exception
    – Andres
    Mar 10, 2021 at 12:30
  • Additionally - java2practice.com/2013/03/23/… - explains other scenarios for @CacheEvict (e.g. Save means next Get should re-evaluate / go to server / whatever)
    – Mr R
    Mar 10, 2021 at 12:32

1 Answer 1

5

Okay - there's an attribute on the annotation you can use. The following example is from (http://websystique.com/spring/spring-4-cacheable-cacheput-cacheevict-caching-cacheconfig-enablecaching-tutorial/)

unless : Conditional Caching, applies to return value of method. Item will be cached, unless the condition mentioned in ‘unless’ met. Note that condition applies to return value of method.#result refers to method return value.

@Cacheable(value="products", key="#product.name", condition="#product.price<500", unless="#result.outofstock")
public Product findProduct(Product product){
..
return aproduct;
} 

So you could have unless="#result.length() == 0" and return an empty string on the error case or any other time you don't want the result cached.

1
  • So you don't have to add an exception - it would achieve the same as the unless but not force the callers to change / deal with the exception.
    – Mr R
    Mar 10, 2021 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.