我在我的网络应用程序和 onContextDestroyed 处理程序中使用计时器任务,我使用以下代码将所有内容设为空:
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);
但是,有时它会打印为空,有时则不是。谁能告诉我问题是什么?如果它不为空,我会得到以下 Catalina 日志输出:
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.
最佳答案
这里有两个问题: 1.但有时它会打印为空,有时则不会 答:我对此不确定,因为这取决于创建和使用计时器任务的代码。
2.如果计时器任务不为空,则会出现此服务器错误“严重:Web 应用程序 [/LoggingMonitor] 似乎已启动名为 [Timer-1] 的线程,但无法停止它” Ans:如果你检查TimerTasks Javadoc,它说“如果任务正在运行,当调用取消发生时,任务将运行完成,但永远不会再次运行”,所以显然,这里任务仍然没有完成,通过contextDestroyed 完成的时间。 为此,您可以检查此方法的返回类型并等待任务完成,然后从上下文销毁方法退出。
关于java - Java 中的计时器任务问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8739385/