views:

90

answers:

2

Is this something you can configure and/or dependent on your Application Server? I am wondering if a singleton object will be reconstructed when you re-deploy the application.

I would rather ask here and try and get a concise answer than googling randomly or resorting to reading J2EE Servlet Specs - I hope people can understand :)

+1  A: 

No, it will not (at least no app server that I know of). The servlet specification gives you the ServletContextListener hook to manage app lifecycle. Some app servers like JBoss have special annotations for singleton beans (@Service), and EJB 3.1 gives you the @Singleton annotation. One other thing to think about when using singletons is what will happen when you cluster you app, you will need High Availability (HA) or use some type of replication, unless you use a share nothing approach. Distributed caches are good for this reason.

disown
+1  A: 

The short answer to this question is no. I don't know of any Application Server that behave this way. However, there are a few things that should be pointed out. Following is a simplistic explanation:

When your application server (ie. JBoss w/Tomcat) starts, it loads some classes in a class loader that will be shared by all applications. When it deploys your application, it will load those classes into its own class loader. When you undeploy your application, that class loader and all its classes will be garbage collected. So when the application is redeployed, all your classes are reloaded, and your singletons will be reinstantiated.

Your application will (in theory, atleast) behave the same after a redeploy, as after a JVM/Application Server restart.

Just a final tip: If you want to use the Singleton Pattern in your enterprise Java application, be sure you know the limitations of singleton objects in an application server environment. You can run into issues if you want to cluster your application, for example.

Bent André Solheim