Java Timer vs ExecutorService?
According to Java Concurrency in Practice:
Timer
can be sensitive to changes in the system clock,ScheduledThreadPoolExecutor
isn't.Timer
has only one execution thread, so long-running task can delay other tasks.ScheduledThreadPoolExecutor
can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providingThreadFactory
).- Runtime exceptions thrown in
TimerTask
kill that one thread, thus makingTimer
dead :-( ... i.e. scheduled tasks will not run anymore.ScheduledThreadExecutor
not only catches runtime exceptions, but it lets you handle them if you want (by overridingafterExecute
method fromThreadPoolExecutor
). Task which threw exception will be canceled, but other tasks will continue to run.
If you can use ScheduledThreadExecutor
instead of Timer
, do so.
One more thing... while ScheduledThreadExecutor
isn't available in Java 1.4 library, there is a Backport of JSR 166 (java.util.concurrent
) to Java 1.2, 1.3, 1.4, which has the ScheduledThreadExecutor
class.
If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
will give you a ScheduledExecutorService
with similar functionality to Timer
(i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer
class). Using a ScheduledExecutorService
also gives you advantages such as:
- You can customize it if need be (see the
newScheduledThreadPoolExecutor()
or theScheduledThreadPoolExecutor
class) - The 'one off' executions can return results
About the only reasons for sticking to Timer
I can think of are:
- It is available pre Java 5
- A similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case)
ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.
An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...
Just look at what each offers to decide.