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.