Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Timer: Is it deprecated?

Tags:

java

timer

I read in a comment to this answer and in many other questions about scheduling (sorry, no references) that java.util.Timer is deprecated. I really hope not since I'm using it as the light way to schedule things in Java (and it works nicely). But if it's deprecated, I'll look elsewhere. However, a quick look at the API docs for 1.6 doesn't say anything about it being deprecated. It's not even mentioned in Sun's Deprecated List.

Is it officially deprecated* and if so, what should I use instead?


* On the other hand, if it's not deprecated, could people stop badmouthing this innocent and brilliantly-implemented set-o-classes?

like image 235
Dan Rosenstark Avatar asked Feb 06 '10 12:02

Dan Rosenstark


People also ask

Is Java util timer thread-safe?

Java Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization.

Is there a timer in Java?

Java programming language provides a class utility known as Timer Task. It allows one to schedule different tasks. In other words, a task can be executed after a given period or at a specified date and time. A Timer in Java is a process that enables threads to schedule tasks for later execution.

What is Java util timer?

The java. util. Timer class provides facility for threads to schedule tasks for future execution in a background thread. This class is thread-safe i.e multiple threads can share a single Timer object without the need for external synchronization.

How do you keep a timer in Java?

Keep a reference to the timer somewhere, and use: timer. cancel(); timer. purge();


1 Answers

As others have mentioned, no it is not deprecated but I personally always use ScheduledExecutorService instead as it offers a richer API and more flexibility:

  • ScheduledExecutorService allows you to specify the number of threads whereas Timer always uses a single thread.
  • ScheduledExecutorService can be constructed with a ThreadFactory allowing control over thread aspects other than the name / daemon status (e.g. priority, ThreadGroup, UncaughtExceptionHandler).
  • ScheduledExecutorService allows tasks to be scheduled with fixed delay as well as at a fixed rate.
  • ScheduledExecutorService accepts Callable / Runnable as it's unit of work, meaning that you don't need to subclass TimerTask specifically to use it; i.e. you could submit the same Callable implementation to a regular ExecutorService or a ScheduledExecutorService.
like image 139
Adamski Avatar answered Sep 29 '22 11:09

Adamski