Can someone please help me to understand why and how Request attributes and local variables are thread safe?
I can have different servlets of a web application setting request attributes, correct? Also, when multiple threads can access a method then their local variables can also be accessed so how local variables become thread safe?
Whenever a request comes for any servlet,the container creates Request, Response objects and also a seperate thread to process that request. Even if another request comes for the same servlet,the container does the same. So there is no link b/w different Requests and the attributes that you set to those Requets.
And come to the Local variables.. As i mentioned earlier that it processes the requests in seperate threads, again there is no link b/w the local variables that you use in any local methods of one request and that of another request.
I got slightly confused with this myself (regarding local variables).
If the variables belong to the *class*, they you're right - they are not safe. Different invocations of the same method by different threads could conflict with each other.
However, if the variables are local to the *method*, each thread gets its own copy. These would be safe.
My confusion stemmed from the fact that these were just called "local variables" and I wasn't sure exactly what they were local to. I remember getting a few practice questions wrong, thinking that they were local to the class.
I can have different servlets of a web application setting request attributes, correct
Setting request attributes means you are setting the attributes for that particular request object. Request objects are created new for each of the user request. So if you set an attribute in this case then it becomes limited only to that request object alone. So it is definitely thread safe to set request attributes.
Setting attributes to session and context objects is never thread safe since they are applied to a larger scope where other servlets /JSP can act on the same.