4

If my Servlet class uses a singleton (such as a manager class), where should it be stored? The servlet itself, or in the ServletContext?

Can a servlet container create more than one instance of my Servlet class to handle requests?

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281

2 Answers2

7

It is certain that there will be only one instance of a Servlet. But still, it's better to store it in the ServletContext. Thus it will be accessible from other servlets as well.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    Indeed and you can eventually use `ServletContextListener` to prepare/create the manager class and put in application scope (the `ServletContext`). See also for example [this question](http://stackoverflow.com/questions/3468150/using-init-servlet). The manager class in question doesn't necessarily need to be a singleton as well. Just create one instance and put it in application scope once. That's all. – BalusC Nov 24 '10 at 11:10
1

You can store it basically anywhere you want; in a session, application context or as a field of that servlet itself. Just be sure to make it immutable since you're dealing with a multithreaded environment and your servlet will be called multiple times at once.

Edit: as Bozho pointed out, using a session might not be the best option, so you should evaluate your needs before putting your singleton in a session.

darioo
  • 46,442
  • 10
  • 75
  • 103