Pure Danger Tech


Rules for good java.util.Timer use

22 Sep 2008

Many people have probably used Timer for some quick one-off timer tasks where using a whole library like Quartz don’t make sense.

One thing to be aware of is that Timer’s constructor will start and spawn a thread. This is a recipe for trouble if you use Timer too casually.

Two good rules of thumb for the use of Timer are:

  1. Always start your Timer as a daemon thread. By default, new Timer() and other constructors use a non-daemon thread which means that the Timer will stick around forever and prevent shutdown. That may be what you expect, but I doubt it.
  2. Always name your Timer. That name is attached to the Timer background thread. That way, if you do something dumb, and look at a thread dump, it will be exceedingly obvious when you’ve started 500 FooBarCleanupThreads.