Where to store Servlet singlets?

If my Servlet class uses a singleton (e.g. manager class), where should it be stored? Servlet itself or ServletContext ?

Can a servlet container create multiple instances of my Servlet class to handle requests?

+4
source share
2 answers

I am sure that there will be only one instance of the servlet . Nevertheless, it is better to store it in a ServletContext . This way it will be accessible from other servlets as well.

+7
source

You can store it anywhere you want; in a session, application context, or as a field in a servlet itself. Just remember to make it immutable, since you are dealing with a multi-threaded environment, and your servlet will be called several times in a row.

Edit: As Bojo noted, using a session might not be the best option, so you should evaluate your needs before placing your singleton in a session.

+1
source

All Articles