0

We have been using following code in production for quite some time now:

@Override
@Transactional(readOnly = true)
@Cacheable("WIDGET_SERVICE_CACHE")
public List<WidgetTO> findAllWidgets() {
    return ...;
}

@Override
@Cacheable("WIDGET_SERVICE_CACHE")
@Transactional(readOnly = true)
public List<WidgetHostTO> findAllWidgetHosts() {
    return ...;
}

As you can see these are 2 different zero-arg methods using the same cache. Now, after reading some documentation on Spring cache it would seem that the name of the method is not taken into account when putting elements in the cache.

What is unclear for us now is that although according to the documentation it should not work, it does. It does not appear that only the parameters are used for the key of the cache. If that's true, what else is taken into account. If not, how come it does work for us and does noet throw (ClassCast)Exceptions?

Stijn Geukens
  • 15,454
  • 8
  • 66
  • 101
  • Which version of Spring are you using? Both DefaultKeyGenerator and SimpleKeyGenerator from version 4.0.0 should cause a collision as they would return a default value given that there are no parameters to the methods annotated. – Louis Jacomet Sep 24 '14 at 09:28
  • Spring 4.0.3 - indeed, according to the doc there should be a collision since the Key will be EMPTY for both methods. Hence my question, why doesn't it? – Stijn Geukens Sep 24 '14 at 09:33
  • You would not have a ClassCastException directly, you would have one only when extracting elements from the `List`. How exactly did you assert that it is working? – Louis Jacomet Sep 24 '14 at 10:34
  • We constantly call these methods (and extract the elements) and to make absolutely sure we have run in debug, put a breakpoint in one of the above methods and confirmed that it is only accessed on the first call and then never again (but gets it from the cache). – Stijn Geukens Sep 24 '14 at 11:08
  • Then the next step, to figure this out, would be to actually look inside the code that does the caching - KeyGenerator and its users. I agree it is puzzling. – Louis Jacomet Sep 24 '14 at 15:43
  • If you are calling the first method and then the second you'll get a `ClassCastException`. If you don't, you may be using a custom `KeyGenerator` or caching may not be enabled at all for that service. They are very good reasons why the method name is not part of the key, check [this comment](https://jira.spring.io/browse/SPR-11736?focusedCommentId=102517&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-102517) for more details. – Stephane Nicoll Oct 01 '14 at 14:42

0 Answers0