----- Original Message -----
From: Ben Coppin <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Sent: Monday, August 16, 1999 11:15 AM
Subject: Re: instance variables in servlets


> sorry - when I said "instance" in this, I don't mean that at all - I
really
> mean I want variables that are independent and unique each time you call
the
> same instance. ie I guess I want:
>
[code removed for brevity]

Class member variables CAN be used in servlets but must be used carefully.
A valid use of them might be to have a class member variable as a request
counter for instance or
to record other state information for the servlet.

Remember that the servlet only has one instance in the servlet engine UNLESS
you implement
SingleThreadModel.

In your example you don't need to have x as a class variable, it can be
local to doGet() which means
that the value of x is then transient and unique for each invocation of the
doGet method.

The use of class member variables is also fraught with threading issues as
well. In your example
you can't be certain that multiple, concurrent requests will set the value
of x to 1 or to 2 at any given time.

For example

Request A comes along, doGet method is called, x is set to 1 by the test.
The thread for A is then suspended by the VM
when Request B comes along. This request causes X to be set to 2 and runs to
completion. The thread for A is then resumed
and also runs to completion but with the incorrect value of 2 in x. These
sorts of bugs can be a real pain to track down
and you need to plan for such eventualities if you want to use class
members.

Hope this helps

Andy Bailey

___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".

Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html

Reply via email to