Singleton in servlet

Can I use Singleton inside the servlet to exchange information between different sessions.

I know that only 1 instance of Servlet is running at any time. Call method for each incoming request. But what about creating another Singleton class (like ShareSingleton) that calls its getInstance () in the servlets init () method. This ShareSingleton can transfer data that should be shared between sessions / reqests.

How risky is this approach in servlets?

+4
source share
2 answers

First ... this is for a better approach to singles: http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html

Secondly: remember that single games are only one for the JVM. Therefore, if you have more than one JVM run, do not expect each singleton to have the same state.

Third: to be safe, I created a singleton instance from the servlet context listener.

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

define a class in your web.xml and create it there. Your singleton will be created when your webapp is launched, and not when n people immediately hit the service method of your servlet.

+8
source

, . , Servlet, , .

, :

private static final Cache<String,String> = //cache

, , . , , , .

0

All Articles