Rules for good java.util.Timer use
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:
- 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.
- 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.