문제

I have error in my applications server logs

SEVERE: A web application appears to have started a thread named [MyThread] but has failed to stop it. This is very likely to create a memory leak.

To resolve this i should stop the thread in contextDestroyed method of My ServletContextListener implementation.

But I am not able to understand how to get reference of my Thread/Runnable so that i can call interrupt().

One solution i have is : putting this thread instance in ServletContext attribute but not sure it is good practice or not. Please suggest if you follow some other approach in your application.

도움이 되었습니까?

해결책

In My Application have a service class(MyServiceClass) which

  1. loads configuration file
  2. validates DB connection
  3. initializes this thread

At the start of application its isConfigurationValid() method is called from ServletContextListener and this method does all above 3 operations.

This class has a instance variable of my Thread type , which is assigned Thread object inside its private initializeThread method. This method is using double check idiom to ensure only one Runnable object is created.

Now I have provided a static getter method for my thread instance field and i interrupt my Thread using this in contextDestroyed method. Below is raw code , please ignore syntax errors if any

MyServiceClass {

    Thread thread;

    public static boolean isConfigurationValid(){
        loadConfigFile(); // private method of same class
        validateDBConfiguration();// private method of same class
        initializeThread();// private method of same class
    }

    private static void initializeThread (boolean usePrimaryPort) {
        {
            if (thread == null){
                synchronized (MyServiceClass.class){
                    if (thread == null){
                        Thread thread = new Thread();
                        Thread.start();
                    }
                }
            }
            return;
        }
    }
    public static Thread getThread(){
        return thread;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top