Aug 23, 2013

How to make thread safe servlet ?

I was asked this question once in an interview Is servlet thread safe ? Luckily they did not drilled much why and how ? I have documented here for the same.

Say loudly two times !! Servlet is not thread safe unless we make it. It is developer responsibility to make servlet thread safe. What does mean thread safe servlet ?
Each servlet request is served by one instance of servlet (Generally speaking) so separate thread is created by container for entertaining each request and servlet container may send concurrent requests through the service method of the servlet. So in order to handle the requests concurrently, if the Servlet Developer make adequate provisions for concurrent processing with multiple threads in the service method then that servlet is called thread safe servlet.
Now question arise how we can make it thread safe?There are few solutions available we will see one by one.

Using ServletThreadModel interface implementation : It is simplest approach but not recommended since it has been deprecated. when we implement this interface servlet container gives guarantee that only one request thread will be present in service method.
What servlet container does then ? Servlet container may either
  • Instantiate multiple instances of the servlet (maintaining a pool of servlet instances). It will be used in a distributed environment where each jvm will be having a servlet instance for serving concurrent request.
  • Serialize requests to a particular instance.  In this case one instance will cater cater multiple request serially
    Reference : SingleThreadModel
By synchronizing service method :  Service method may be appended with synchronized keyword so that only one thread request will be under service method at a time. But in this way performance will be very poor.So it is also not recommended.Then what we need to do ?
A simple rule which need to be followed to make Servlet shared among all active thread in thread safe manner is:
"just do not assign request or session scoped data as servlet instance variables, only as method local variables."
Lets see using an example :
public class SimpleServlet extends HttpServlet {
  private Object NotThreadSafe;
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {
    Object ThreadSafe;
    NotThreadSafe = request.getParameter("foo");  
                 //Its Bad Design, Shared among all requests!
    ThreadSafe = request.getParameter("foo"); 
                // OK, this is thread safe.
Here NotThreadSafe is an instance variable so it is shared among all thread and it is not thread safe.But at same time ThreadSafe is local variable and is unique for all thread and it is thread safe.

=================End of the article===================
Happy learning!!.

Related post, you may like it:
1. Servlet Life Cycle