Does Spring @Cacheable block a block when accessing more than 1 thread?

If the method marked by @Cacheable takes 10 minutes and two threads t1, t2 access this method.

t1 refers to time 0 (the cache method is now executed for the first time) t2 at time t1 + 5 minutes

Does this mean that t2 will not access the data for about 5 minutes, since t1 has already launched the @Cacheable operation, and it should complete after 5 minutes (since it works for 5 minutes) or will a new call to @Cacheable called by t2 ?

+5
source share
3 answers

If the result of the first execution was not cached, the second call will continue.

You should understand that @Cacheable centered around the contents of the cache (and not specifically the context of the thread's execution [well, like, the cache should still be thread safe]). When the method is executed, the cache is first checked to see if the key exists: if t1 takes some time, its result will not be cached, so simultaneous actions will be performed without taking into account t1

+2
source

As the colossus explained, the cache is checked before calling the method. So, if the element is not in the cache (as it will be the case with t1 + 5 minutes), the method call will also be executed for the stream t2.

There is no "blocking" in the @Cacheable annotation. t2 will call the method as if there was a cache miss, and therefore t2 will also take 10 minutes to complete the same method.

+1
source

No lock on @Cacheable.

But you can use cache cache strategy in cache implementation. The first query found by miss is responsible for restoring the cache. Other requests are awaiting cache recovery.

  • To implement a local cache, use ReadWriteLock . See net.sf.ehcache.constructs.blocking.BlockingCache .
  • To implement remote caching, use the ghetto central lock.
+1
source

Source: https://habr.com/ru/post/1206737/


All Articles