Drawbacks of Timer
The Timer facility manages the execution of deferred ("run this task in 100 ms") and periodic ("run this task every 10 ms") tasks. However, Timer has some drawbacks, and ScheduledThreadPoolExecutor should be thought of as its replacement.
A Timer creates only a single thread for executing timer tasks. If a timer task takes too long to run, the timing accuracy of other TimerTasks can suffer.
Another problem with Timer is that it behaves poorly if a TimerTask throws an unchecked exception. The Timer thread doesn't catch the exception, so an unchecked exception thrown from a TimerTask terminates the timer thread.
Timer also doesn't resurrect the thread in this situation; instead, it erroneously assumes the entire Timer was cancelled. In this case, TimerTasks that are already scheduled but not yet executed are never run, and new tasks cannot be scheduled.
package timer;
public class OutOfTime {
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
System.out.println("Begin task 1 at " + new Date());
timer.schedule(new ThrowTask(), 1);
Thread.sleep(1000);
System.out.println("Begin task 2 at " + new Date());
timer.schedule(new ThrowTask(), 1);
Thread.sleep(5000);
System.out.println("Finish at " + new Date());
}
static class ThrowTask extends TimerTask {
public void run() {
throw new RuntimeException();
}
}
}
Output of program:
Begin task 1 at Sat Dec 12 22:21:50 CST 2009
Exception in thread "Timer-0" java.lang.RuntimeException
at timer.OutOfTime$ThrowTask.run(OutOfTime.java:21)
at java.util.TimerThread.mainLoop(Timer.java:527)
at java.util.TimerThread.run(Timer.java:477)
Begin task 2 at Sat Dec 12 22:21:51 CST 2009Exception in thread "main" java.lang.IllegalStateException: Timer already cancelled.
at java.util.Timer.sched(Timer.java:369)
at java.util.Timer.schedule(Timer.java:185)
at timer.OutOfTime.main(OutOfTime.java:14)
You might expectthe program to run for six seconds and exit, but what actually happens is that it terminates after one second with an IllegalStateException whose message text is "Timer already cancelled".
Resources: