When many request access the servlet then it will be multi threaded,means each thread will execute the servlets’ service method(EX:dopost or doget) in its own stack
1) all objects are in Heap memory. Even IF a object is created inside a method ,it will exit in heap memory.
2) In the above code Variable “a” is create a new instance of class “A” and keep it in Heap Memory.
3) For example if Three requests access the servlet abc ,means three Threads execute the dopost method. so that It create three separate Instance of Class “A”.
4) So in application, every thing is written servlets’ service method only.
As far as I know, as long as you don't store the instance anywhere (e.g., session.putValue...) you're ok.
That is, there's no way to reference the instance outside of the method AND the object's lifecycle is only for the lifetime of the method call.
Joined: Jun 04, 2007
John Kimball wrote:As far as I know, as long as you don't store the instance anywhere (e.g., session.putValue...) you're ok.
Not really. Just consider this case
Here we don't store counter's reference anywhere else but we are still in trouble.
Imagine ThreadOne has executed LineA and has gone into RegionX
Now ThreadTwo comes in and executes LineA.
So the counter is now 2.
ThreadOne gets the control back and executes LineB. When what was expected is a value 1, what is obtained is 2.
No "tend" about it. Instance variables are not thread-safe.
I'd say they're potentially not thread-safe; whether there is or is not actual thread (un)safety depends on the usage. For example, if an instance variable is populated in a servlet's init method, and not modified later, it's still thread-safe.
Also, as mentioned, it's possible to make instance variables thread-safe by using synchronization or Locks.