Announcement Announcement Module
Collapse
No announcement yet.
HOW-TO: ApplicationContext memory leaks in Spring 3.0.x. Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • HOW-TO: ApplicationContext memory leaks in Spring 3.0.x.

    When we upgraded our jBoss server, we also upgraded from Spring 2.5.6 to 3.0.2. Soon after we started having memory problems.

    Our research identified the cause to be a change in Spring context handling - that causes a memory leak in legacy code.

    I hope this information will save some of you from the pain we had to endure. Good luck.

    THE PROBLEM:

    Most of us learned to get the context with code like this:
    Code:
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    Much of our code does exactly this and we never had a problem in the past.

    But as of version 3.0.x, you need to call ctx.close() or Spring will retain a reference to that context.

    In most scenarios this is not a big deal - if your application instantiates the context only once - since the JVM will be released at the end of the app, or if it is a webapp... it only happens once. Even if you don't change a thing, you will not notice memory leaks.

    But if you instantiate the context multiple times or run under a scheduler that calls your app multiple times... your memory will leak instances of the Spring context and the objects it instantiates.
    There is also a bug in 3.0.0 that defeats the normal fix. The bug was patched in a later version.

    THE SOLUTION:

    The correct solution is to close the context as follows
    • Instantiate the context only once per application.
    • Call the .close() method after you are done using the context and its beans.
    • Use ConfigurableApplicationContext since ApplicationContext does not have a .close() method.

    Of course, closing the context in legacy applications might not be so easy.

    For some legacy apps, the application design might make it difficult to close the context at application end. Since management will not be keen to embark in a complete redesign, you need a band-aid that has less impact. Making the context a static variable is such a band-aid. It is not as good as closing the context when done, but at least it will contain the leak and keep duplicate instances to a manageable volume.

  • #2
    Could this perhaps relate to:
    https://jira.springsource.org/browse/SPR-7385
    Then your solution is simple: Just reset the world.

    Otherwise: I've never used ClasspathXmlApplicationContext in a JEE Container, but only for standalone application. I allways preferred ContextLoaderListener or Spring Dispatcher Servlet.

    Comment


    • #3
      I think that is an unrelated memory leak.

      Comment

      Working...
      X