File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Instance variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Instance variables" Watch "Instance variables" New topic

Instance variables

Chris Brat
Ranch Hand

Joined: May 22, 2003
Posts: 108
I have read that it is never a good idea to declare static variables (because of the huge number of servlets that can access the same variable at the same time), and that if they are used they should be declared as final...
my question is whether it is accepted to declare instance variables or should values that are required rather be kept in the session or passed as parameters (ex. between doGet method and doPost in the same servlet).
I know this is most definitely a silly question, so please be gentle in your responses.

Neeraj Singhal
Ranch Hand

Joined: Aug 13, 2000
Posts: 49
Hi Chris
The instance variables in the servlets are shared by all the threads accessing it. Hence, if one thread changes the value, it will be reflected by all th threads.
So, its better to put such varaibles in session, that are specific to a client.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Static final should be fine for something that you want to share among all instances and all threads, maybe configuration stuff. "final" is important because you promise the compiler you'll never change the value and the compiler enforces the promise.
If values change in member variables, you have to be careful to synchronize access. Something as simple as

could have unpredictable results because of other threads. There may be times you want to do this ... maybe a configuration variable can be changed via an administrative function. For example, an admin might turn logging on and off.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Instance variables
jQuery in Action, 3rd edition