It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized, used in readonly manner, or shared values can be stored in a session, as hidden fields or in database table. The single threaded model can adversely affect performance and hence has been deprecated in the servlet specification 2.4.

Thread safety tips from Thread safe issues in Servlets

1. local variables: each thread gets its own copy of the local variables.
2. instance variables: not thread safe. There is only one copy of the instance variable per instance of 3. the servlet. Use instance vriables for variables that can be initialized at servlet startup and can be used througout life of the servlet (i.e connection variable).
4. class variables: not thread safe also. Use static on variables where value remains constant.
5. context scope (getServletContext()): not thread safe
6. session: not thread safe also. try synchronized (session){}
7. request: thread safe. Paased as a a parm of the service() method.

Also look at Java World: Write thread-safe servlets

DeveloperWorks: Are all stateful Web applications broken?

Advertisements