File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes static variable in a servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "static variable in a servlet" Watch "static variable in a servlet" New topic

static variable in a servlet

ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
Defining a static variable in a servlet can be useful in any scenerio?

Static variable are shared between instances but servlet has only one instance at a time (except clustered environment).

So I guess, except clustered environment, no body will use static member in servlet.

Is it right?

narender kaasam

Joined: May 15, 2006
Posts: 28
A very good question.I agree with your expalnation.Because only one instance will be created in servlet.So there is no use os Static varibales.
Purushoth Thambu
Ranch Hand

Joined: May 24, 2003
Posts: 425
Not always some J2EE server allows you to create pool for SingleThreadedServlet. For example in WebLogic you can configure to have more than one instance of the same servlet.
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

You can also create multiple servlet instances from the same class by adding new servlet entries in your deployment descriptor.
I this case both servlets (even though they have different names) will share the same static variables.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
Thanks All.
Nice answers.
steve souza
Ranch Hand

Joined: Jun 26, 2002
Posts: 862
Also even with one servlet instance running a static variable is fine if it is thread safe. - a fast, free open source performance tuning api.
JavaRanch Performance FAQ
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63548

I use static variables in servlets all the time -- mostly for "constants".

[Asking smart questions] [About Bear] [Books by Bear]
I agree. Here's the link:
subject: static variable in a servlet
It's not a secret anymore!