Skip to content

Target Cache gets checked twice for every cache hit [SPR-11592] #16216

@spring-projects-issues

Description

@spring-projects-issues

Jacques Stadler opened SPR-11592 and commented

Problem

Whenever you execute a cached method that has already been executed once, and therefore its result can be fetched from the cache, there will be 2 cache hits that happen for one execution of this method.
See e.g. this snippet from the referenced GitHub project:

      ServiceToCache obj = (ServiceToCache) context.getBean("serviceToCache");
      Cache cache = (Cache) context.getBean("cache");

      String key = "1";
      String result1 = obj.returnSomeString(key);
      // Before it calls the method the cache is checked
      verify(cache, times(1)).get(key);

      String result2 = obj.returnSomeString(key);
      // Here we would expect that the cache was only called twice, but it is being called 3 times.
      verify(cache, times(3)).get(key);

I would expect that if I execute a cached method once, there should only be one cache hit, not two.

Solution

As I see it the problem lies in org.springframework.cache.interceptor.CacheAspectSupport.execute(Invoker, CacheOperationContexts):

                // Collect puts from any @Cachable miss
		List<CachePutRequest> cachePutRequests = new ArrayList<CachePutRequest>();
                // NOTE: This produces the first cache hit
		collectPutRequests(contexts.get(CacheableOperation.class), ExpressionEvaluator.NO_RESULT, cachePutRequests, true);

		ValueWrapper result = null;

		// We only attempt to get a cached result if there are no put requests
		if (cachePutRequests.isEmpty() && contexts.get(CachePutOperation.class).isEmpty()) {
                // NOTE: This produces the second cache hit
			result = findCachedResult(contexts.get(CacheableOperation.class));
		}

I suppose the cached value should be fetched once, before calling the two methods (collectPutRequests, findCachedResult) above.


Affects: 4.0.2

Reference URL: https://github.com/stadler/poc-spring-cache

Issue Links:

0 votes, 5 watchers

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions