Singleton in a Servlet

java, servlets, singleton

Solution

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.

Problem

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 ?

Original source