views:

567

answers:

2

Hi all,

for many reasons, it is not good practice to use threads inside servlet. java.util.Timer seems like wrapper to threads. so also it is not safe to use it ? if yes, what is the safest way to schedule task in servlet ?

thanks,,,

A: 

Yes. It's perfectly safe. The servlet container will look after threads for HTTP requests, but you can spawn aditional threads yourself, whether their lifetime is restricted to that of the request, or for longer.

e.g. a common pattern is to spawn a long running processing thread. Servlet requests would put work items on a queue (for out-of-band processing) and the long running processing thread would handle these work items.

Here's an article from OReilly detailing timer usage in servlets and EJBs.

Brian Agnew
even I use it in doPost oe doGet methods ?
worldpython
Yes. That's fine
Brian Agnew
there is a reference or benchmark to test that ?
worldpython
See the references above.
Brian Agnew
many thanks, it is ok
worldpython
+4  A: 

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.

mhaller
there is another safe wrapper ?
worldpython
thanks for your effort
worldpython
define "safe" please. Do you mean "secure access" or "bug-free" or "easy to use" or ...?
mhaller
i mean bug-free
worldpython
it is very bug-free. most problems with Threads and Timers in applications come from applicaton developers, not from JVM or appserver developers :)
mhaller
thanks for help
worldpython