0

我在我的网络应用程序和 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);

但是,有时它会打印为 null,有时则不是。谁能告诉我问题是什么?如果它不为空,我会得到以下 Catalina 日志输出:

严重:Web 应用程序 [/LoggingMonitor] 似乎已经启动了一个名为 [Timer-1] 的线程,但未能停止它。这很可能造成内存泄漏。

4

1 回答 1

1

这里有两个问题: 1.但有时它打印为空,有时它不打印 Ans:我不确定这一点,因为这取决于创建和使用 timertask 的代码。

2.如果timertask 不为空,那么您会收到此服务器错误“严重:Web 应用程序 [/LoggingMonitor] 似乎已经启动了一个名为 [Timer-1] 的线程,但未能停止它” TimerTasks Javadoc,它说“如果在调用取消时任务正在运行,则任务将运行到完成,但永远不会再次运行”,所以很明显,到 contextDestroyed 完成时,这里的任务还没有完成。为此,您可以检查此方法的返回类型并等待任务完成,然后退出上下文销毁方法。

于 2012-01-05T08:16:33.663 回答