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

For many reasons, it is not recommended to use streams inside the servlet.

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

+6
java multithreading timer servlets scheduling
source share
2 answers

Yes, you can use timers.

One important important thing is to cancel this timer when the servlet is stopped. If you forget to cancel the timer, your webapp will suffer from memory leaks (class leaks, as the timer thread is bound to WebappClassLoader via ContextClassLoader) and cannot be deployed several times.

+9
source share

Yes. It is completely safe. The servlet container will monitor the streams for HTTP requests, but you can create your own streams yourself, regardless of whether their lifetime is limited by the request or longer.

eg. a common template is to create a long flow of processing. Servlet requests put work items in the queue (for out-of-band processing), and a long process thread processes these work items.

Here's an article from OReilly that details usage of a timer in servlets and EJBs.

+2
source share

All Articles