Rookie
Rookie

Reputation: 8800

Issue with Timer Task in Java

I am using a timer task in my web app and in onContextDestroyed handler, I am using the following code to make everything null:

System.out.println("contextDestroyed - fileWatcherTask:"+fileWatcherTask);
System.out.println("contextDestroyed - mytimer:"+mytimer);

fileWatcherTask.cancel();
mytimer.cancel();

System.gc();

if (fileWatcherTask != null) {
    System.out.println("fileWatcherTask is not null");
    fileWatcherTask=null;
}

if (mytimer!=null)
{
    System.out.println("mytimer is not null");
    mytimer=null;
}

System.out.println("contextDestroyed - logTimerTask After invoking cancel mytimer: "+mytimer);
System.out.println("contextDestroyed - logTimerTask After invoking cancel fileWatcherTask: "+fileWatcherTask);

However, sometimes it is printing as null and sometimes it’s not. Can anyone tell me what the problem is? And if it is not null the I get the following Catalina log output:

SEVERE: The web application [/LoggingMonitor] appears to have started a thread named [Timer-1] but has failed to stop it. This is very likely to create a memory leak.

Upvotes: 0

Views: 897

Answers (1)

NiranjanBhat
NiranjanBhat

Reputation: 1832

there are two questions here: 1.but sometimes it is printing as null and sometimes it doesn't Ans: I am not sure about this,as this depends on the code where the timertask is created and used.

2.If the timertask was not null, then you get this server error "SEVERE: The web application [/LoggingMonitor] appears to have started a thread named [Timer-1] but has failed to stop it" Ans: If you check the TimerTasks Javadoc, it says "If the task is running when the call to cancel occurs, the task will run to completion, but will never run again" , so obviously, here the task is still not completed, by the time contextDestroyed gets completed. for this you can check the return type of this method and wait till the task is completed and then exit from the context destroyed method.

Upvotes: 1

Related Questions