Multithread safe servlets

This posts explains the multithreading safety problem and explains how it can be prevented. I’m writing about it because recently I’ve fixed a bug in Openbravo ERP related with issue, and I would like to remind developers about this problem to take it into account.

The way Tomcat manages servlets is creating one instance of the object and having multiple threads invoking methods on that instance, each of these threads is serving each of the multiple simultaneous request. Thus a single servlet instance can be used at the same time by different users.

All this must be kept in mind when developing servlets in order to prevent dirty global properties readings. Let me explain through a little example, let’s define a servlet:

public class Test extends HttpServlet {
private String st;

  public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws IOException, ServletException {
    st = readStringFromSomewhereElse();
    //... do other stuff here

In this case there could be two users accessing the doPost method simultaneously using the same instance of Test class, the first one could set the st as “A” and before printing its value the second one could set it as “B”, the the first one would print “B” instead of “A” as it would expect. In this case this property would have a static behavior.

So this pattern should be avoided when developing servlets, this is, there should not be global properties modified in the doPost method (or in any other one called from it).  Generally, this can be easily solved using variables inside the doPost method instead of global properties. In fact, global properties should be initialized just once in the init method and not modified afterwards.