tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Christopher Schultz <ch...@christopherschultz.net>
Subject Re: Tomcat reuses threads and connection instances
Date Wed, 26 Jan 2011 23:37:02 GMT
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Blake,

On 1/26/2011 4:05 PM, Blake McBride wrote:
> The first time a particular web service is called tomcat starts a thread to
> run it on and creates an instance of the class that implements the web
> service.  All fine.  However, if after the first call to the web service
> completes another call to the same web service occurs, tomcat reuses the
> same thread and the same instance.  Of course this gives me old values for
> thread local storage and instance variables for that web service.

Oh noes!!!111!!!ELEVEN

Seriously, this is how the server world works.

> This is highly unexpected.

Perhaps by you, but this behavior is entirely intentional.

> Is there a way to configure tomcat to have it give me a new instance of the
> web service class each time?

That depends: when you say "web service", what do you mean? Are you
using a library like Apache Axis or do you have a (relatively) simple
servlet handling the requests?

The rules of thumb are:

1. Don't use ThreadLocal unless you
  a) Know what you're doing
  b) Clean up after yourself
     and
  c) Know what you're doing

2. Don't use any class members that aren't expected to be used for all
   requests for all time. Basically, that means don't use them. Instead,
   use locals in your service() (or doGet/doPost/whatever) method
   and/or use request attributes to store your data.

> In terms of the repeated thread use and thread local storage I have, for the
> time being, started manually resetting the thread local storage.  Is there a
> conventional solution to this problem?

Your thread should reset ThreadLocals when you're done using the thread:
at the end of the request. Don't forget to handle error conditions and
clean up in finally blocks.

Why are you using ThreadLocals in the first place? The only legitimate
uses I've seen for them are performance optimizations where the
ThreadLocal actually /should/ outlive the request and weird stuff like
passing data to Log4j loggers through lazy API (non-)usage. I'm not
convinced ThreadLocals are a good idea at all.

- -chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEUEARECAAYFAk1AsB4ACgkQ9CaO5/Lv0PB0KgCgq/oBUPbokm0RxU2TJUUbTc5o
P14AmNWkViWqWDzayx274G/ghV0oStw=
=xJXy
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org


Mime
View raw message