Suresh said:
Hi,
Does static variables in servlets make any sense. As far as I understand, a
servlet object is created only once (correct me if I am wrong). But it may
be called from many threads. So declaring a variable as static should be the
same as declaring it as a ordinary variable.
A servlet class may be instantiated more than once by a servlet
container, under the following conditions:
(1) The servlet implements SingleThreadedModel
or
(2) The container releases one instance and then later instantiates
another. The container does not have to use any instance for any
particular amount of time.
Distributed servlet containers add more possibilities, but they're not
really relevant here.
In any case, a static variable is _not_ functionally equivalent to an
instance variable in a servlet. I recommend you do not use mutable
static variables in your servlet; if you need to store persistent state
then use context or session attributes, as appropriate.
Actually, I also recommend that you not use mutable instance variables
in your servlets. Mutable static and instance variables are invitations
to thread safety problems. That particular problem goes away for
instance variables if you implement SingleThreadedModel, but is always
there for static variables. SingleThreadedModel can hamper performance.
Could someone give me some pointers where I can find more info ?
Read the Servlet API, available free from Sun. I don't have the
specific URL handy, but start at
http://java.sun.com.
John Bollinger
(e-mail address removed)