I currently have to make a specific Java servlet implementation thread-safe.
The code is not written by me and I wasn’t involved in it’s design or anything. I “just” have to make it thread-safe 🙂
I’m not a beginner in thread-safety, but not a professional either. Servlets are (more or less) completely new to me. I’ve worked through some tutorials and know the basics about servlets, but that’s it. All tutorials I could find about making servlets thread-safe were rather superficial and I still have some unanswered questions which I just can’t seem to find answers for. Some help would be much appreciated.
1.) From what I understand, HttpServletRequests and HttpServletResponses are not shared between different threads, so I don’t need to synchronize read- and write access on them (is this correct?). But what about HttpServletRequestWrappers etc.?
2.) I have to synchronize access to the ServletContext object returned by getServletContext(), especially if I use setAttribute() on it, right?
3.) HttpServletRequests has a getCookies() method. Are these Cookies potentially shared between different requests or does every request have it’s own Cookie objects (even if they represent the same “real” cookie)? Asked differently: Do I have to synchronize the access to the returned cookie objects?
Thanks for taking time to read my questions. I’m looking forward to your answers 🙂
Servlets are not thread safe because the application server can maintain a single instance of the servlet or a pool of instances and share them across multiple incoming requests. And hence, servlets should not have any state (i.e servlet object level variables are not thread-safe). Servlet specification used to have
SingleThreadModelinterface earlier to enforce a given servlet to be thread-safe but that’s been deprecated since 2.3, I guess.Responses:
Right, these are paramters to the HTTP methods like doGet and doPost and hence accesses to these need not be synchronized.
Right because getServletContext() returns a context level object that is accessible to all servlets and all threads running a given servlet.
Every request comes with its own set of cookies. Again, this is obtained fromt the method parameter, HttpServletRequest and so accesses need not be synchronized.