Multi Threading a Servlet


Web tier: servlets, JSP, Web frameworks: Multi Threading a Servlet

  1. Multi Threading a Servlet (1 messages)

    There seem to be a lot of messages and discussions on subjects such as EJB, CORBA, IDL.......My question or the thread that I want to start is about multi threading a servlet.

    How can we make a servlet thread safe? I do know about the SingleThreadModel and the Synchronization......

    Let us assume for a moment that we are not to use either of the methods discussed above, what would be the optimal way of designing a servlet? I do hope to start a good discussion chip in all of you......
  2. Multi Threading a Servlet[ Go to top ]


    We can make a servlet thread safe without any of the methods like synchronization or SingleThreadModel.

    Your idea of coding a servlet should be.
    The primary aim of coding a servlet is to get parameters from the request. Process the paramters sent with some business logic and send the response as html or what ever may be the response type.

    If you want to make a servlet thread safe then we have to avoid the declaration of global variables in the servlet class. If you declare any variables at the class level then the changes made by one thread can be seen by another.

    Consider this scenario. It is a login servlet. The user id should be made disabled if the user has entered the wrong password for say 3 times. If we want to achieve this the ideal choice is to go for session beans. But when it has to be done using servlet, the program logic compels us to declare a common class level variable for storing the number of times(counter) for the same login, and the actual login name. But when it is tested in a multi-user environment the changes made by a servlet thread can be seen by other thread (i.e) when one user typed the wrong password. The other thread shows two times as counter.

    So this cannot achieved by declaring common variables. The way we achieved the result for the above problem by making use the Session API of the servlets.

    But if the idea of the discussion is to make servlet thread safe for mission critical database transactions. Then it would be appropriate for coding those things in EJB.

    Hope this answers your question.