Tuesday, May 14, 2013

How do you make a Servlet thread safe?


A typical (or default) Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method. The multithreading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner. Having large chunks of code in synchronized blocks in your service methods can adversely affect performance and makes the code more complex.

Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null
interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure

Thread safety:
􀂃 Instance pooling where container maintains a pool of servlets.
􀂃 Sequential processing where new requests will wait while the current request is being processed.


Best practice:

 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 or used in
read-only manner or shared values can be stored in a database table. The single threaded model can adversely
affect performance.


No comments:

Post a Comment