2

How many instances of a servlet are created by the servlet container after loading it? is it only one?

Neel Salpe
  • 1,287
  • 3
  • 15
  • 26

3 Answers3

9

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
4

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...

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

Yes, one instances with multiple threads.

Eric Wilson
  • 57,719
  • 77
  • 200
  • 270