I’m currently having an issue with stopping a background thread in a webachive. I currently tie it in the war’s deployment, and destroy it when the archive is un-deployed.
The threads starts up without issue, but when I close the archive, It seems to lose the handle on the thread. In the below case: st is null when the contextDestroyed method is called.
This is an issue as Tomcat notes the thread as orphaned in its warning about memory leaks.
public class LimitOrderContextListener implements ServletContextListener {
static Logger logger = Logger.getLogger(LimitOrderRuntime.class.getName());
private SwiftThread st = null;
/**
* Initializes this listener when this war's context is initialized
*/
public void contextInitialized(ServletContextEvent sce)
{
try {
if ( (st == null) || (!st.isAlive()) ) {
LimitOrderRuntime lor = new LimitOrderRuntime();
SwiftThread st = new SwiftThread(lor);
st.start();
} else {
st.gracefulStop();
st.join(2000);
}
} catch(Exception e) {
logger.warn("Unable to properly load thread! " +
e.getMessage() + " --cause " + e.getCause());
e.printStackTrace();
}
}
/**
* When this war is destroyed/stopped, stop the thread.
*/
public void contextDestroyed(ServletContextEvent sce)
{
try {
boolean success = st.gracefulStop();
if (!success) {
st.interrupt();
}
} catch (Exception e) {
logger.warn("Unable to properly release thread! " +
e.getMessage() + " --cause " + e.getCause());
e.printStackTrace();
}
}
}
In your
contextInitializedmethod, you’re redeclaring st as a local variable, rather than initializing the instance variable with the thread.Replace
with