Trouble implementing Singleton pattern in Tomcat web application due to Class Loader
- by jwegan
I'm trying to implement a Singleton in Tomcat 6.24 on Linux with x86_64 OpenJDK 1.6.
My application is just a bunch of JSPs and some static content and the JSPs make calls to my Java code. Currently the web.xml just looks like this:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<description>
App Name
</description>
<display-name>App Name</display-name>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>pages/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Before when I was trying to load my Singleton it was getting instantiated twice since the class was getting loaded by two different class loaders (I'm not sure why) and each loader would create an instance of the singleton which is not acceptable for my application. I finally figured out if I exported my code as a jar and put it in $CATALINA_HOME/lib then there was only one instance, but this is not an elegant solution.
I've been googling for hours, but I haven't come up with anything yet. I'm wondering if there is some other solution. Currently I'm not precompling my JSPs, could this be part of the problem? Could I write a servlet to ensure the singleton is created? If so how do I do that?