Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
11-14-2008, 07:44 PM #1
- Join Date
- Nov 2008
- Thanked 0 Times in 0 Posts
Static/Instance Variables in Servlets
I was curious about the reasons NOT to use static or instance variables in servlets.
I know one reason is because that multiple threads have a chance of overwriting the variables causing inconsistencies in the application, but i was also wondering what other reasons there are for not doing this?
Here is an except from somewhere:
What about using static variables in servlets?
There are three points to consider:
1. Are your static variables read-only? If not, you need to synchronize while updating such variables.
2. In case your static variables aren't read-only, you should also consider the effects of the distribution of the application. How do you make sure that static variables in different JVMs are consistent?
3. How do you protect your static variables/methods from other Web applications deployed on the same container (and JVM)?
To avoid these issues, consider storing such data in ServletContext objects.
In short, Servlets are always a single instance, and always use the same instance.
If there are multiple threads running, it's entirely possible that both are using the same object at the same time, causing variables to be overwritten. If your servlets only read from the request, write to the response, and save information in local variables (that is, variables declared within a method), you needn't worry about the interaction among these threads. Once any information is saved in non-local variables (that is, variables declared within a class but outside any specific method), however, you must be aware that each of these threads has the ability to manipulate a servlets non-local variables. Without precautions, this may result in data corruption and inconsistencies.
Synchronization is kind of another sub topic under this, and kind of corrects certain problems with multi-threading, but can also be dangerous. i.e Deadlocks or hang-ups
But i am trying to come up with some more reasons... Any more help would be appreciated.
11-16-2008, 03:20 PM #2
can you think of scenarios where you would want to use non-final static variables other than counters and caches?
You never have to change anything you got up in the middle of the night to write. -- Saul Bellow