2

According to the java docs, it says that If SingleThreadModel is used there are two ways a servlet instance will be created and used 1. Create one servlet instance and make the service() method synchronized and thus allow only one thread to execute the service method. 2. Create a pool of servlets and serve the request by using one servlet instance from the pool for each request.

THe question which I want to ask is I have also read a new Servlet instance is created and destroyed for every request. Now which one is correct

ravikumar
  • 101
  • 1
  • 3

2 Answers2

0

Here's what the spec says (version 3.0, section 2.2):

For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.

In the case where a servlet was deployed as part of an application marked in the deployment descriptor as distributable, a container may have only one instance per servlet declaration per Java Virtual Machine (JVMTM)1. However, if the servlet in a distributable application implements the SingleThreadModel interface, the container may instantiate multiple instances of that servlet in each JVM of the container.

Note that you should really not use the single thread model. Just make sure your servlet is thread-sae. A servlet is typically stateless, so you don't have anything to do to make it thread-safe.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I like your answer. +1 from my side. If you have time, can you elaborate a bit more on your answer given here: http://stackoverflow.com/questions/8687765/servlet-synchronization-when-multiple-instances?rq=1# – Farhan stands with Palestine Nov 22 '14 at 17:59
0

From the docs for SingleThreadModel:

Ensures that servlets handle only one request at a time

This is in essence a way to make non thread-safe servlet code work. Note that the container is free to choose any of the two implementations to adhere to the spec:

  1. Create a single instance of the servlet and ensure that it handles only one request at a time
  2. Create a pool of servlet instances and hand over a request to an available servlet instance.
spinlok
  • 3,561
  • 18
  • 27