Can a declaration of a static ApplicationContext cause a memory leak? (Spring 3)

I have a code that I use from another command, and I spent several days trying to track down a suspicious memory leak in my application. I get an OutOfMemory error after a few redploys. I used several leak tracking tools, including MyKit Java Profiler and IBM Support Assisant Memory Analyzer. My application is a Spring 3.0.5 J2EE application running on WebSphere 6.1 using annotation-controlled spring-mvc controllers.

Most of the research I have done points to a class that I find very suspicious, we will call it MyFactory, and it looks like this:

import org.springframework.context.ApplicationContextAware; public final class MyFactory implements ApplicationContextAware { //this should be changed to be non static after getInstance is removed private static ApplicationContext applicationContext; public MyFactory() { //empty } public static SettingObjectFactory getInstance() { return (MyFactory) applicationContext.getBean("MyFactory"); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { MyFactory.applicationContext = applicationContext; } } 

There is a whole bunch of other logic in this class that I forgot, which basically reads data from the database and stores it in memory (near the cache). However, this class seems to hang with ApplicationContext after the application has been re-installed.

Is this class a class loader hanging on the ApplicationContext or does not allow to completely clear it? I know that we no longer need the getInstance method, and I don’t see the need for this class to have a static ApplicationContext - it seems to me that Spring should ensure the singletonity of this class.

+6
source share
1 answer

Yes, a static link to ApplicationContext can cause a memory leak in many settings. The way that some applications and JVms interact with loading classes means that objects referenced in static fields can be stored in the PermGen memory pool (at least in the Sun Hotspot JVM). Spring appcontexts can be very large object graphs, depending on how your context config looks.

The only permanent solution for this that I have found is to avoid hot deployments in production environments, which is generally related to the problem of disposing of pergents. However, this is still annoying in the development environment.

+6
source

Source: https://habr.com/ru/post/887089/


All Articles