What can be the reasons for a TimerTask to stop running in a Tomcat Servlet

人盡茶涼 提交于 2019-12-20 06:35:18

问题


I suspect an exception could make the TimerTask stop running in which case I most likely need a second timetask to monitor that the first is still running?

Update

Thanks for the answers. I had inherited this code so a bit ignorant...

I just saw that if I throw an uncaught exception in my job the TimerThread ceases to run forever.

Run method of TimerThread showed that if an exception is thrown, my scheduled thread never runs again.

public void run() {
    try {
        mainLoop();
    } finally {
        // Someone killed this Thread, behave as if Timer cancelled
        synchronized(queue) {
            newTasksMayBeScheduled = false;
            queue.clear();  // Eliminate obsolete references
        }
    }
}

The end of the stacktrace will be:

at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)

So temp solution is to catch EVERYTHING... longer term solution is to move to better scheduling as BalusC states.


回答1:


TimerTasks die when an uncaught exception is thrown (whether it's running in tomcat or not is unrelated). The easiest way to resolve this is to catch RuntimeException in your run method, and log & continue if that's what you want.

It's also advisable to catch Throwables as well and log it before you rethrow it so that you can see the stacktrace in your logs, like this:

    try{
        doRun();
    }catch (RuntimeException e){
        logger.error("Uncaught Runtime Exception",e);
        return; // Keep working
    }catch (Throwable e){
        logger.error("Unrecoverable error",e);
        throw e;
    }


来源:https://stackoverflow.com/questions/18965239/what-can-be-the-reasons-for-a-timertask-to-stop-running-in-a-tomcat-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!