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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With