How many instances of a servlet are created by the servlet container after loading it? is it only one?
3 Answers
Servlets do not adhere to the Singleton pattern. Servlet classes have a public constructor which already violate the singleton pattern. The creation of servlets is by default just the Just Create One pattern. Technically, the container can create as many of them as it needs. Especially if the servlet happens to implement the (deprecated) SingleThreadedModel
interface so that the container can create a pool of those servlet instances in order to improve performance.
However, it is true that the same instance can be shared among multiple requests. That's why it's very important to not assign any request/session scoped data as an instance variable of the servlet. It would be shared among multiple requests.
Servlets at its own adheres to the Template Method pattern by the way. This is not related to creation, it is just a behavioral pattern.
See also:
-
Thank you BalusC for comprehensive reply .By the way I am regular visitor to u r JSF blog :) ! – Neel Salpe Jun 09 '11 at 20:24
Only one singleton servlet instance is created per whole application (lazily by default), so it must be thread-safe (watch out for servlet fields). However request and response objects are created per request and thus are thread-safe.
On the other hand, HTTPSession
is one per user session (duh...), so if the same user accesses the application with two simultaneous requests, consider synchronizing on session. As you can see, servlet threading model is a bit complicated...

- 334,321
- 69
- 703
- 674
Yes, one instances with multiple threads.

- 57,719
- 77
- 200
- 270
-
-
I wouldn't expect that the servlet spec specifies that. Are you interested in how a particular implementation handles this? (Tomcat, Jetty, JBoss?) – Eric Wilson Jun 09 '11 at 19:46
-
I'm not sure what you are asking. If the answer given by @BalusC is not helpful enough, perhaps you should ask a new question. – Eric Wilson Jan 16 '14 at 19:03