Drawbacks of Timer


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:

Java Concurrency in Practice

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)