mirror of
https://github.com/spring-projects/spring-framework
synced 2026-06-08 17:33:33 +00:00
ca62119cb3
Since Spring Framework 4.2, DefaultContextCache supported an LRU (least recently used) eviction policy via a custom LruCache which extended LinkedHashMap. The LruCache reacted to LinkedHashMap's removeEldestEntry() callback to remove the LRU context if the maxSize of the cache was exceeded. Due to the nature of the implementation in LinkedHashMap, the removeEldestEntry() callback is invoked after a new entry has been stored to the map. Consequently, a Spring ApplicationContext (C1) was evicted from the cache after a new context (C2) was loaded and added to the cache, leading to failure scenarios such as the following. - C1 and C2 share an external resource -- for example, a database. - C2 initializes the external resource with test data when C2 is loaded. - C1 cleans up the external resource when C1 is closed. - C1 is loaded and added to the cache. - C2 is loaded and added to the cache before C1 is evicted. - C1 is evicted and closed. - C2 tests fail, because C1 removed test data required for C2. To address such scenarios, this commit replaces the custom LruCache with custom LRU eviction logic in DefaultContextCache and revises the put(MergedContextConfiguration, ApplicationContext) method to delegate to a new evictLruContextIfNecessary() method. This commit also introduces a new put(MergedContextConfiguration, LoadFunction) method in the ContextCache API which is overridden by DefaultContextCache to ensure that an evicted context is removed and closed before a new context is loaded to take its place in the cache. In addition, DefaultCacheAwareContextLoaderDelegate has been revised to make use of the new put(MergedContextConfiguration, LoadFunction) API. Closes gh-21007