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.
so everything is Thread-safe.??
Joined: Jun 04, 2007
From my understanding, the code that you posted should be thread-safe. The variable is just a local variable. But when you change it to
now its not thread-safe.
To say in other words, local variables are thread safe, while instance variables are not.
Also context-scoped attributes and session-scoped attributes would not be thread safe as such.
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.
jacob deiter wrote:IN a Web application every thing inside dopost or doget method only.So the entire application is thread safe,then when to use "syncronized" Statement
I have never had an occasion to use synchronized.
Joined: Mar 22, 2005
Bear Bibeault wrote:
Thus instance variables tend to be thread-unsafe.
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.