Originally posted by Sani babangida:
So are you implying if a user changes the value of a static variable, the change would reflect across all users of the servlet web page
Not only that, because there is only one instance of the servlet, even instance variables will be shared across all threads.
You must write servlets to be thread-safe.
That means avoiding both class and instance variables that are not meant to be shared across threads. And of course, read/write variables that are to be shared must be sychronized appropriately.
Best practices dictate avoiding read/write variables in servlets, either static or instance, in favor of scoped variables in the appropriate scope.
[ March 02, 2007: Message edited by: Bear Bibeault ]
so I never really thought of what would happen in a clustered environment if you did
Well since we now have two instances (say) of a server running, we must have two instances of the servlets running, one in each JVM. So I guess each static variable would relate itself to the servlet it belongs to.
Which would then put the two Servlets out of sync
It would be the container's job to keep them in sync wouldn't it ?. In any case I would think twice before using public static variables or instance variables and when you couple that with clustering, the scenario can be quite rare.
I am also not certain about the granularity of the syncing. Say a servlet updates a public static variable and then crashes the very next line. Will the synced backup servlet contain the updated value ? I think it should not. Perhaps every complete execution of a doGet or doPost would be considered something like a transaction to commit changes to a synced servlet.
The only variables I ever declare at class level in a servlet are static final variables.
Originally posted by John Meyers:
It would be the container's job to keep them in sync wouldn't it ?.
When I said about one instance of servlet I have talked about "one server" case (without clustering). If you have distributed web application you will have one instance of servlet per JVM. Fields will not be synchronized by containers.
Originally posted by Bear Bibeault:
The bottom line is that it is asking for trouble to use read/write class or instance variables in a servlet. And as the context scopes are availabe to store data in a safe fashion, there's no need, so don't do it.
Agree. Servlet should be stateless and thread-safe.
FYI: servlet context will not be synchronized by containers (in case of distributed web application). Only session will be synchronized.
SRV.2.2 Number of Instances
SRV.7.7.2 Distributed Environments