Hi,
Thanks for reading this.
I am developing a webapp and do not understand the following:
In my app, I create a Timer when the servlet starts.
When tomcat stops, I try to stop the timer in order to avoid memory leaks.
My question is: why do I get a NullPointerException while trying to access
mytimer in contextDestroyed().
The simplified code:
public class myclass extends HttpServlet implements ServletContextListener {
java.util.Timer mytimer;
int testint;
public void init() throws ServletException {
mytimer = new Timer("__test__");
TimerTask taskPerformer = new TimerTask() { public void run() {
whatever_function(); } };
mytimer.scheduleAtFixedRate(taskPerformer, 10, 10, 864000);
testint = 12;
}
public void contextDestroyed(ServletContextEvent event) {
System.out.println("Inside contextDestroyed, testint="+testint);
try {
mytimer.cancel();
}
catch (Exception e) {
System.out.println("An error occurred inside
contextDestroyed(): "+e);
}
}
public void contextInitialized(ServletContextEvent event) {
// Nothing here
}
public void destroy() {
// Nothing here
}
}
The Output:
May 26, 2010 8:06:30 PM org.apache.catalina.core.StandardService stop
INFO: Stopping service Catalina
Inside contextDestroyed(), testing=12
An error occurred inside contextDestroyed(): java.lang.NullPointerException
May 26, 2010 8:06:30 PM org.apache.catalina.loader.WebappClassLoader
clearReferencesThreads
SEVERE: A web application appears to have started a thread named [__test__] but
has failed to stop it. This is very likely to create a memory leak.
What disturbs me, is that my other variable "testint" is accessible within
contextDestroyed, but not mytimer.
If I save my timer in init() like this:
ServletContext sc = getServletContext();
sc.setAttribute("mytimer", mytimer)
and if I modify contextDestroyed() so that it accesses my timer through
ServletContext
ServletContext context = event.getServletContext();
Timer mytimer2 = (Timer)context.getAttribute("mytimer");
then I have no problem stopping it, making the tomcat warning disappear.
I'd like to understand why it is so.
Thank you very much in advance
___________________________________________________________
NEU: WEB.DE DSL für 19,99 EUR/mtl. und ohne Mindest-Laufzeit!
http://produkte.web.de/go/02/
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]