Thursday, November 20, 2008

Time's Up

I'm certainly not the first person to say this, but it bears repeating, using Timer in the post Java 5 world is not a good idea. I got bitten by Timer's lack of exception handling again recently. If you must use a Timer and are relying on it to be long-lived, make sure the run() methods on your tasks can't throw any unchecked exceptions, because if any exceptions manage to leak out of the run() method, the timer thread will terminate and no more tasks will run. I used to use Timer in situations where I wanted to be able to cancel tasks, since TimerTask exposes a cancel() method. What I failed to realize was that you can do the exact same thing using ScheduledExecutorService using the ScheduledFuture object that is returned when one of the schedule methods is invoked. It's a bit more cumbersome to cancel tasks this way since you may have to keep references to both the task object and the future object, but it wouldn't be too difficult to create a custom class to manage this.

No comments: