I have code where I schedule a task using java.util.Timer. I was looking around and saw ExecutorService can do the same. So this question here, have you used Timer and ExecutorService to schedule tasks, what is the benefit of one using over another?
Also wanted to check if anyone had used the Timer class and ran into any issues which the ExecutorService solved for them.
According to Java Concurrency in Practice:
Timercan be sensitive to changes in the system clock,ScheduledThreadPoolExecutorisn’t.Timerhas only one execution thread, so long-running task can delay other tasks.ScheduledThreadPoolExecutorcan be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providingThreadFactory).TimerTaskkill that one thread, thus makingTimerdead 🙁 … i.e. scheduled tasks will not run anymore.ScheduledThreadExecutornot only catches runtime exceptions, but it lets you handle them if you want (by overridingafterExecutemethod fromThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.If you can use
ScheduledThreadExecutorinstead ofTimer, do so.One more thing… while
ScheduledThreadExecutorisn’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 theScheduledThreadExecutorclass.