Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton in a Servlet

Can i use a singleton within a servlet to share information between diffrent session.

I know that only 1 instance Servlet is running at any time. Calling service method for each incoming request. But how about creating another Singleton class (for eg: ShareSingleton) which calls its getInstance() in the servlets Init() method. This ShareSingleton can carry data that needs to be shared between sessions/reqests.

Is it risky to use such an approach in servlets ?

like image 724
Linus Avatar asked Jan 11 '23 21:01

Linus


1 Answers

First..see this for the best approach of singletons: http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html

Second: Remember singletons are only single to the JVM. So..if you have more than one JVM running do not expect each singleton to have the same state.

Third: To be safe, I would instantiate the singleton from a listener of the servlet context.

see http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html

define a class in your web.xml and instantiate it there. Your singleton will be created when your webapp starts up rather than when n people hit the service method of your servlet at once.

like image 67
Slihp Avatar answered Jan 19 '23 00:01

Slihp