This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Some mock exams say that HttpServletRequest and HttpServletResponse objects are thread safe. According to specification, implemenations of request, response objects are not guaranteed to be thread safe.
I was going through that link but still confused with the explanation.
It also says that the method parameters and local variables are threadsafe.
I don't think method parameters are thread safe.Say if i have an instance variable and passing the reference to the method called by a thread then how come the method parameters are thread safe because it is pointing towards my instance variable which could be accessed by different thread at the same time.
The specification says somthing like this
Implementations of the request and response objects are not guaranteed to be thread
safe. This means that they should only be used within the scope of the request handling
References to the request and response objects should not be given to objects
executing in other threads as the resulting behavior may be nondeterministic. If
the thread created by the application uses the container-managed objects, such as
the request or response object, those objects must be accessed only within the
servlet’s service life cycle and such thread itself should have a life cycle within
the life cycle of the servlet’s service method because accessing those objects
after the service method ends may cause undeterministic problems. Be aware
that the request and response objects are not thread safe. If those objects were
accessed in the multiple threads, the access should be synchronized or be done
through the wrapper to add the thread safety, for instance, synchronizing the call
of the methods to access the request attribute, or using a local output stream for
the response object within a thread.
Could you please explain what the specification mean by that?
Also it says that the reference to those objects should not be given outside the servlet's service method.
But what happens if we forward the request using RequestDispatcher in which case the request created for Servlet1 is given to the Servlet2 and the servlet1 service method is completed but still Servlet2 has reference to those objects.
I checked this using the hashcode method on the request object and they both returns the same value which mean i believe the request object in Servlet2 is referring to request object that was created for Servlet1.