> I have created an object that is used in a servlet on tomcat. It is
> very important that this object and all of the information it contains
[quoted text clipped - 14 lines]
> servlet and the object are affecting other instances of the servlet
> and object? How do I stop that from occurring?
På Thu, 22 Feb 2007 21:03:03 +0100, skrev lambelly <lambelly@gmail.com>:
> I guess, to phrase it better, I am looking for a way to make class
> variables thread safe in tomcat.
Use a ThreadLocal, or even better in the web application case, use request
attributes.
So, either
// in the servlet
static final Threadlocal clientHolder = new ThreadLocal();
// in the request code
clientHolder.put(new Client());
// For retrieval
Client threadsClient = clientHolder.get();
Or
request.setAttribute(CLIENT_ATTR_NAME, new Client());
Client requestClient = (Client) request.getAttribute(CLIENT_ATTR_NAME);
> I guess, to phrase it better, I am looking for a way to make class
> variables thread safe in tomcat.
>> I have created an object that is used in a servlet on tomcat. It is
>> very important that this object and all of the information it contains
[quoted text clipped - 14 lines]
>> servlet and the object are affecting other instances of the servlet
>> and object?
Yes, if they are class variables.
>> How do I stop that from occurring?
The simplest answer is to make them instance variables. Class variables are
shared between every object of that class. Besides being shared, in a
multi-threaded servlet container all access to those variables should be
synchronized.
What values are you talking about? Are these part of the class Client, or part
of the servlet? If they are part of the servlet the same rule applies, class
variables for the servlet will be shared between different servlet instances.

Signature
Nigel Wade, System Administrator, Space Plasma Physics Group,
University of Leicester, Leicester, LE1 7RH, UK
E-mail : nmw@ion.le.ac.uk
Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555
Joe Schlobotnick - 25 Feb 2007 20:18 GMT
<snip>
> If they are part of the servlet the same rule applies, class
> variables for the servlet will be shared between different servlet instances.
While this is true, you must beware that Servlet instances are reused by
multiple HTTP requests. So even though a variable is defined as an
instance variable in the Servlet, it can be helpful to treat them like
class variables that are shared by multiple instances.
I've seen this in practice: a servlet with an instance variable
indicating the language in which the user wants to see the page, where
that language variable is used in SQL queries to retrieve content from
the database in the appropriate language. Under high load, a user could
see the page switch languages half way down as another user request
started being serviced by the same servlet instance and switched the
"instance" variable's value.
..Joe