tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From David Delbecq <>
Subject Re: Can servlets safely spawn threads?
Date Mon, 29 Jan 2007 13:09:28 GMT
En l'instant précis du 01/29/07 11:33, Danny Ayers s'exprimait en ces
> Hi,
> I would be grateful is someone could answer these questions:
> * Can servlets safely spawn threads?

short answer, yes. They *can*. However that does not mean all spawned
Threads are safe.
> * If so, under what conditions?
1) Your servlet must always take care to finish all Threads it has
spawned. This mean when servlet gets unloaded, you must have provided a
mecanism in your servlet to stop all running threads your servlet has
created. Remaining Threads not handled by container can either cause
tomcat to not stop when requested or prevent garbage collecting of
webapp when reloading.

2) Never have your spawned thread access request-time specific
informations. This mean no request/response object passed to spawned
threads. Avoid passing the Session object too. Lots of stuffs exposed by
tomcat to servlet are assuming only one thread will work on it, the http
thread, as such, there is quite a good amount of possible use of
ThreadLocal variables.

3) if possible, spawn daemon threads, and name your threads, this ease a
lot debugging.

I have seen working web application spawning their own thread.
Applications using the Quartz scheduler are an example of them. The
Quartz scheduler spawns a few threads a provides mecanism for servlet to
stop them.

In general, try to avoid spawning your own thread. however, it's not
always possible, and the Specs does not forbid spawning thread. But
handle them properly. The best way, if you need your own thread, is to
never use in the spawned thread object managed byt the container.

> I tried to find the answers searching the web, but found conflicting
> views.
> So I thought it worth asking about a specific servlet container
> implemention.
> I'm trying to make a very simple asynchronous messaging system on top of
> HTTP. What I have in mind requires that the servlet called would complete
> the request-response in "reasonable" time, yet may initiate other
> processes
> that are potentially long-running. The easiest approach would be to
> have the
> servlet spawning another thread in which to run the other process, and
> return a response to the client immediately. But is this possible without
> running straight into concurrency breakage?
> More background at :
> Thanks,
> Danny.

To start a new topic, e-mail:
To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message