The CaffeineCacheManager will potentially cause a memory leak if the getCache method is called with thousands of different cache names since a new cache instance will be created and put into the cacheMap for each cache name in dynamic mode. And each cache instance may retain about 200 KB of memory (The retained memory will be different from different cache configurations). That means, it would cause OOM if there are significant enough calls to the getCache method with different names.

I can understand that it may not be recommended to call the getCache method with so many different names, however, as a commonly used library, it would be good to add logic to defend from such a situation occurring. E.g. 1. Release cache instances if there are no cached data items. 2. Prevent cacheMap to be too large, at least, adds a limitation to the map size.

https://github.com/spring-projects/spring-framework/blob/0c39fff83141235324241468235982a54b7afe18/spring-context-support/src/main/java/org/springframework/cache/caffeine/CaffeineCacheManager.java#L194

Comment From: jhoeller

In general, it is up to the application to call getCache with a sensible number of cache names. I don't really see an obvious default limit that we could set there, just potentially a custom configurable limit on CaffeineCacheManager. You can lock down the cache names through pre-configuring them via setCacheNames already, effectively bounding the number of caches. Analogously, we could provide a separate setCacheLimit method (or the like) for a maximum number of dynamically created caches, returning null from getCache for any further requests for non-existing cache names.

Comment From: snicoll

What would be the acceptable behaviour when called with too many caches? Right now, it increases memory up to a point where the JVM fails. This looks like the right behaviour to me. Returning null would lead to another exception (cache xyz does not exist). Throwing an exception wouldn’t be much better than the status quo.

I don’t think we should do anything here.

Comment From: jhoeller

Returning null would be equivalent to requesting a non-declared cache name in the pre-configured case, suggesting to the caller that no such cache was defined and therefore none was to be used. But yeah, I don't see much benefit in this either. If only certain caches are supposed to be used to begin with, pre-configuring the actual cache names is definitely a better choice, rather than arbitrary ignoring further cache requests at some point.