Reputation: 113
I'm wondering why the SimpleKeyGenerator in Spring 4+ doesn't just return an Integer representing a hash of the method parameters? Since the returned SimpleKey stores the actual method parameters, it was leading to excessive memory usage and garbage collection in my web application, bringing the whole thing down every two days or so. (Some of these parameters were fairly large collections of strings.) I've since had to revert to my own KeyGenerator implementation, which is basically a mishmash of code I've seen elsewhere.
I'm using EhCache 2.9 as my cache implementation.
Upvotes: 0
Views: 1808
Reputation: 206936
From the API docs of SimpleKeyGenerator
:
Unlike
DefaultKeyGenerator
, no collisions will occur with the keys generated by this class.
If SimpleKey
would only store the hash code and not the actual parameters itself, this could not be guaranteed. A hash code is not a unique key, you can have different objects (or combinations of parameters, in this case) which have the same hash code (in fact, that's unavoidable, because there are more possible objects than possible hash codes - see pigeonhole principle).
In other words, without storing the parameters themselves, the equals()
method of SimpleKey
cannot be implemented correctly - it needs to call the equals()
methods of all parameters and not just compare hash codes.
See also the API docs of DefaultKeyGenerator
- that implementation of KeyGenerator
indeed only stores hash codes and it's deprecated precisely because it's possible that collisions can occur, leading to incorrect behaviour.
If this causes an excessive memory usage problem, then configure your cache differently so that it doesn't grow too large or make sure you don't pass large objects to SimpleKeyGenerator
for generating keys.
Upvotes: 1