Skip to content

Default KeyGenerator doesn't work for methods with arguments of array types [SPR-11505] #16130

@spring-projects-issues

Description

@spring-projects-issues

Craig opened SPR-11505 and commented

The way that Spring calculates cache keys doesn't work for methods that take parameters of array types. For example, define this method:

@Cacheable
public String test(String[] one)
{
return "something";
}

Then run:

String[] alpha = {"a","b","c"};
String[] beta = {"a","b","c"};
test(alpha);
test(beta);

The result is 2 executions of the method body (where in my opinion, only 1 is expected) and 2 cache entries (again, only 1 is expected).

The result of this problem is that methods with array type parameters will always result in a cache miss (the body is always executed) and a cache put is always done after the method is executed (filling the cache with garbage that's never used again). This second part is particularly troublesome, as useful stuff ends up getting evicted as the cache fills with garbage.

The problem is that DefaultKeyGenerator (Spring < 4) and SimpleKeyGenerator (Spring 4 and later) use hashCode(), and the hashCode of an array isn't specifically defined, and bubbled up to Object.hashCode() which uses the memory address of the array. Since each array, even if it has the same items in it, has a different address, the hashCode is always different.

Changing the implementation to use deepEquals/deepHashCode fixes this problem.


Affects: 3.1.4, 3.2.8, 4.0.2

Referenced from: commits e50cff4, 6d8f3a0, 70155e9

Backported to: 3.2.9

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: backportedAn issue that has been backported to maintenance branchestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions