Question

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.

Était-ce utile?

La solution

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;
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top