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
    System.out.println(st);
  }
}

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.

10 thoughts on “Multithread safe servlets

  1. CSStungfurher says:

    Hi can you help me, pls i’ve downloaded the source code but when i want to compile de code the next problem happend in openbravo POS
    Exception in thread “AWT-EventQueue-0” java.lang.RuntimeException: Uncompilable source code
    at com.openbravo.data.loader.SerializerWriteBasicExt.writeValues(SerializerWriteBasicExt.java)
    at com.openbravo.data.loader.PreparedSentence.openExec(PreparedSentence.java:141)
    at com.openbravo.data.loader.BaseSentence.exec(BaseSentence.java:42)
    at com.openbravo.data.loader.BaseSentence.exec(BaseSentence.java:38)
    at com.openbravo.pos.forms.DataLogicSystem.setResource(DataLogicSystem.java:201)
    at com.openbravo.pos.forms.DataLogicSystem.setResourceAsProperties(DataLogicSystem.java:241)
    at com.openbravo.pos.forms.JRootApp.setActiveCash(JRootApp.java:294)
    at com.openbravo.pos.forms.JRootApp.initApp(JRootApp.java:175)
    at com.openbravo.pos.forms.JRootFrame.initFrame(JRootFrame.java:55)
    at com.openbravo.pos.forms.StartPOS$1.run(StartPOS.java:107)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    Like

  2. Heglize says:

    спреи и крема для похуденияв тибетской медицине диета при циррозевариант диеты № 5ппохудеть на апельсинахдиеты которые реально помогли а месяцпохудеть аудиокнигадиетологи в тамбовекнига как выбрать пол ребенка французская диетакосметика виши для похудениядиабет сахарный диетадиабет 2 диета физичиская активнастьправильное питание после перенесенного инфаркта миокардашелтон артотрофия основы правильного питаниякодировка от лишнего весамосковский центр реабилитации похудениедиетологи о пользе морского рисакефир с корицей и имбирем диетамнения о поясе для снижения весапояс похудения саунаэффективные упражнения для снижение веса

    Like

  3. Нужны услуги опытного креативного ведущего праздников? Значит наше предложение – это то, что Вам нужно! Агентство Family Works оказывает полный комплекс услуг в Москве. Нам по силу любые торжества: Новый Год, свадьба, детский праздник, юбилей и др. Обращайтесь к профессионалам если хотите, чтобы Ваш праздник был действительно веселым, интересным и запоминающимся! Посмотреть фотографии с мероприятий и узнать больше об услугах можно на сайте FamilyWorks.Ru.

    Like

Leave a comment