Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use java.util.Timer inside a servlet ?

For many reasons, it is not good practice to use threads inside a servlet.

java.util.Timer seems like wrapper around a thread. So, is it also not safe to use it? If so, what is the safest way to schedule a task in a servlet?

like image 518
mebada Avatar asked Dec 25 '09 12:12

mebada


People also ask

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.

Does Java Timer create a new thread?

There it states: "Corresponding to each Timer object is a single backgroundthread that is used to execute all of the timer's tasks, sequentially." - so yes, each Timer has its own thread but if you schedule 2 tasks on the same timer they will be executed sequentially.

How do you schedule a Timer in Java?

Java Timer schedule() methodThe schedule (TimerTask task, Date time) method of Timer class is used to schedule the task for execution at the given time. If the time given is in the past, the task is scheduled at that movement for execution.

What is Timer delay Java?

Timers are constructed by specifying both a delay parameter and an ActionListener . The delay parameter is used to set both the initial delay and the delay between event firing, in milliseconds. Once the timer has been started, it waits for the initial delay before firing its first ActionEvent to registered listeners.


1 Answers

Yes, you can use Timers.

One important thing to remember is to cancel that Timer when the servlet is stopped. If you forget to cancel the Timer, your webapp will suffer from memory leaks (classloader leaks, since the Timer's Thread is bound to the WebappClassLoader via its ContextClassLoader) and cannot be deployed multiple times.

like image 110
mhaller Avatar answered Oct 25 '22 22:10

mhaller