Hi,

You could also eliminate the mix & match and add a finally, with the following servlet code for example:

public void init() throws ServletException {
               boolean initOk = false;
                mytimer = new Timer("__test__");
                try {
                        TimerTask taskPerformer = new TimerTask() { public void 
run() { whatever_function(); } };
                        mytimer.scheduleAtFixedRate(taskPerformer, 10, 10, 
864000);
                                testint = 12;
                        initOk = true; // as last
                } finally {
                        if (!initOk) {
                                mytimer.cancel();
                        }
                }
         }

public void destroy() {
System.out.println("Inside destroy, testint="+testint);
    try {
        mytimer.cancel();
    } catch (Exception e) {
System.out.println("An error occurred inside contextDestroyed(): "+e);
}
}

I added a finally / cancel in the init method, because as Kostantin Kolinko said yesterday, if there is an exception in the init method after a timer creation, then the destroy method is not called and the timer is never canceled even if your webapp is unusable (and Tomcat 6.0.26 will warn about that timer).

I supposed here that your init method is not so simplified.

bye, Emeric

Le 26/05/2010 21:26, Caldarale, Charles R a écrit :
From: roberto calosino [mailto:devn...@web.de]
Subject: Re: Stopping a Timer in contextDestroyed() to avoid memory
leaks results in a NullPointerException

"You can optionally also let your servlet both extend
HttpServlet and implement ServletContextListener"
It is also said that "it is not always considered a
good practice."

Why is that so ?
Because, as you have inadvertently discovered, separate instances of the class 
are created for each purpose.  If you make the mytimer field static (along with 
any others you want to use in both instances) you won't have a problem.

  - Chuck


THIS COMMUNICATION MAY CONTAIN CONFIDENTIAL AND/OR OTHERWISE PROPRIETARY 
MATERIAL and is thus for use only by the intended recipient. If you received 
this in error, please contact the sender and delete the e-mail and its 
attachments from all computers.




---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org
For additional commands, e-mail: users-h...@tomcat.apache.org

Reply via email to