Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables.
Now, if 2 or more users send request to this server then what happens to the session variables? Will they all be common for all the users or they will be different for each user. If they are different, then how was the server able to differentiate between different users?
One more similar question, if there are n
users accessing a particular servlet, then this servlet gets instantiated only the first time the first user accessed it or does it get instantiated for all the users separately? In other words, what happens to the instance variables?
No. Servlets are not Thread safe
The is allows accessing more than one threads at a time
if u want to make it Servlet as Thread safe ., U can go for
Implement SingleThreadInterface(i)
which is a blank Interface there is nomethods
or we can go for synchronize methods
we can make whole service method as synchronized by using synchronized
keword in front of method
Example::
or we can the put block of the code in the Synchronized block
Example::
I feel that Synchronized block is better than making the whole method
Synchronized