2

A web container will typically create a thread to handle each request. To ensure that a servlet instance handles only one request at a time, a servlet can implement the SingleThreadModel interface. If a servlet implements this interface, no two threads will execute concurrently in the servlet’s service method.A web container can implement this guarantee by synchronizing access to a single instance of the servlet or by maintaining a pool of web component instances and dispatching each new request to a free instance.

Could someone clarify the bolded part of the above paragraph ?

Doesn't each servlet would have only one instance of it in a web container?

Learner2011
  • 287
  • 2
  • 6
  • 25
  • at startup, create x (x > 1) instances of the servlet. when a request comes in send the request to one of these servlet instances. Similar to connection pooling for database connections (similar in concept) – DwB Sep 11 '14 at 18:23

1 Answers1

3

Doesn't each servlet would have only one instance of it in a web container?

No, that is not always true. The web container manages the lifecycle of servlets (it is responsible for creating and managing instances of servlets). The Java EE specification does not guarantee that there will be only one instance of your servlet class, so you should not write your servlets in a way that depend on this.

As the description explains, the web container might make multiple instances of your servlet class to efficiently and concurrently handle requests if your servlet implements SingleThreadModel.

It is better to write your servlet in such a way that it does not need to implement SingleThreadModel - write your servlet code in a thread-safe way.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • Is it possible to limit the number of instances of the servlet(in the case when a servlet implements SingleThreadModel)in a server? – Learner2011 Sep 11 '14 at 18:31
  • 1
    Stay away from SingleThreadModel. Seriously. It's an instant bottle neck. Even if you decide to go for it, if you need to know the number of instances, you're doing something terribly wrong. So don't do it, i.e. do not keep any state in the Servlet (or, if you really, really must, which you probably don't, carefully manage the shared state for concurrent access). – kaqqao Sep 11 '14 at 19:15
  • @Learner2011 Not in a standard way; maybe your specific Java EE server has some setting for it, but it's not standard Java EE functionality. In general, this is not something you need to worry about. Let the web container manage servlet instances. I agree with kaqqao: don't write your servlets in a way that causes you to need this functionality. Make your servlets stateless and thread-safe. – Jesper Sep 11 '14 at 19:24
  • 1
    @Learner2011 you can get more info here: [How do servlets work? Instantiation, session variables and multithreading](http://stackoverflow.com/q/3106452/1065197) and in the links in the accepted answer. – Luiggi Mendoza Sep 11 '14 at 19:37