How are exceptions handled in @Cacheable method that uses sync=true

Viewed 447

I am using @Cacheable in Spring Boot 2.0 with EHcache, with sync=true.

I understand that if we set sync=true, all threads wait until one thread fetches the value to cache by executing the method that used @Cacheable.

What happens if there is an exception in that method? Do the other threads keep waiting or is the lock released?

1 Answers

The idea of the @Cacheable annotation is that you use it to mark the method return values that will be stored in the cache.

Each time the method is called, Spring will cache its return value after it is called to ensure that the next time the method is executed with the same parameters, the result can be obtained directly from the cache without the need to execute the method again. Spring caches the return value of a method with key-value pairs. The value is the return result of the method.

Now coming to your question, lets first understand what is Synchronized Caching

Synchronized Caching

In a multi-threaded environment, certain operations might be concurrently invoked for the same argument (typically on startup). By default, the cache abstraction does not lock anything, and the same value may be computed several times, defeating the purpose of caching.

For those particular cases, you can use the sync attribute to instruct the underlying cache provider to lock the cache entry while the value is being computed. As a result, only one thread is busy computing the value, while the others are blocked until the entry is updated in the cache

The sole purpose of sync attribute is that only one thread will build the cache and other will consume the cache. Now if there is an exception during execution of method, which means the thread which acquired the lock will never set anything in cache and exit, now next thread will get it's chance to get lock because nothing would be there in cache, and if during second thread's execution exception occurs, then next thread will get it's chance until one threads sets the cache for same parameters.

Related