Thread Safe Servlet

  • A typical 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.
  • Alternatively it is possible to have a single threaded model of a servlet by implementing SingleTreadModel.
  • The container will 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.