We are using the Spring TestContext framework (SpringJUnit4ClassRunner) for JUnit test execution. We are hitting OutOfMemoryErrors when running a large number of tests in batch. The problem is that the ApplicationContext objects are building up in the ContextCache (org.springframework.test.context.ContextCache), consuming a large amount of memory.
We have worked around the problem by annotating @DirtiesContext on each JUnit test class.
However, it seems that this issue could be avoided if ContextCache wrapped its cached ApplicationContexts in WeakReferences. This seems to be a best practice when caching potentially large objects such as these.
#10532 Allow for concurrent test execution in the TestContext framework
#16200 Introduce system property to disable context caching in the TestContext framework
#12710 Limit size of context cache in the TestContext framework ("is superseded by")
Prior to this commit, the ContextCache in the Spring TestContext Framework (TCF) cached ApplicationContexts in a ConcurrentHashMap using strong references. This practice can occasionally lead to OutOfMemoryErrors when running a large number of tests in a test suite with varying context configuration since the context cache becomes overpopulated over time.
This commit addresses this issue by using Spring's ConcurrentReferenceHashMap which uses SoftReferences for both the keys (i.e., MergedContextConfiguration instances) and values (i.e., ApplicationContexts) stored in the map that backs the ContextCache.
Resolving this issue as "Won't Fix" since the use of the soft or weak references would prevent the TestContext framework from properly closing application contexts that get transparently evicted by the garbage collector.
An an alternative, we will instead have to investigate a more robust solution like the one proposed in #12710.