Timer & TimerTask versus Thread + sleep in Java
Timer/TimerTask also takes into account the execution time of your task, so it will be a bit more accurate. And it deals better with multithreading issues (such as avoiding deadlocks etc.). And of course it is usually better to use well-tested standard code instead of some homemade solution.
The advantage of TimerTask is that it expresses your intention much better (i.e. code readability), and it already has the cancel() feature implemented.
Note that it can be written in a shorter form as well as your own example:
Timer uploadCheckerTimer = new Timer(true);
uploadCheckerTimer.scheduleAtFixedRate(
new TimerTask() {
public void run() { NewUploadServer.getInstance().checkAndUploadFiles(); }
}, 0, 60 * 1000);
From the Timer
documentation:
Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
So Prefer ScheduledThreadExecutor
instead of Timer
:
Timer
uses single background thread that is used to execute all of the timer's tasks, sequentially. So tasks should complete quickly else it will delay the execution of subsequent tasks. But in case ofScheduledThreadPoolExecutor
we can configure any number of threads and can also have full control by providingThreadFactory
.Timer
can be sensitive to system clock as it makes use ofObject.wait(long)
method. ButScheduledThreadPoolExecutor
is not.- Runtime exceptions thrown in TimerTask will kill that particular thread, thus making Timer dead where as we can handle that in
ScheduledThreadPoolExecutor
so that the other tasks are not impacted. Timer
providescancel
method to terminate the timer and discard any scheduled tasks, however it doesn’t interfere with the currently executing task and let it finish. But if timer is running as daemon thread then whether we cancel it or not, it will terminate as soon as all the user threads are finished executing.
Timer vs Thread.sleep
Timer makes use of Object.wait
and it is different from Thread.sleep
- A waiting (
wait
) thread can be notified (usingnotify
) by another thread but a sleeping one cannot be, it can only be interrupted. - A wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not.
- While sleeping does not release the lock, waiting will release the lock for the object wait is called upon.