I know that for each request to a servlet a the doPost() or doGet() methods are executed and that the code wirtten inside init() method is initialised only once. But what about the code written outside all these methods?
Is that code also threaded? I mean varibles declared in that part, if they are modified in the doPost()
, will those changes be reflected for other requsts to the servlets?
In a normal servlet container, there is only one instance of the servlet object. This object may be used by any number of Threads - one Thread per request. Managing the lifetime of a servlet instance is up to the servlet container.
Hence, when changing the value of a class variable in any method (including init()), it will affect all subsequent requests. Changing or declaring a local variable within your method of course does not influence anything, as the next time the method is called, the local variable is created again (and gets destroyed by the garbage collector when the method is finished).
By defaut Servlets are not thread safe. A single servlet instance will be invoked for many clients. It is absolutely wrong to have state stored inside the servlet as instance variables.
References:
Using session as instance variable
Is a Servlet thread-safe
Write thread safe servlets
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With