This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
My application provides some xml parsing functionalities. The parsed xml turns to a object. Most of the code is generic java code. The calling part is from java servlet(JSP). The parsing process is time cusuming and I fount that the parsed object could be reused(read-only). So I try to implement a caching mechanism which will put the object into cache if we found out that the xml is the same. As we can see, the cache has to across requests and sessions. I can use a singleton which contains a Hashtable(static) to store the objects and use a timer to purge the objects if the objects are too old(e.g. 1 hour). As I was told that that could be a dangerous implementations in that we could easily got memory leak. What should I be causious? Is there a problem using singleton with Tomcat? Bujin
In general, singletons are a poor choice for most applications (search for "singleton" in the "OO, Patterns and UML" forum to read lots of discussion). This is especially true when the context of your code already provides a fine alternative. Every application running in a servlet container has available to it an "application context" (also known as "servlet context"), which can be used to store any objects that you wish - such objects are available to all servlets, JSPs and filters in the application. I strongly suggest that you either put your parsed objects directly into the application context, or that you put a Map into the application context and store your parsed objects into that. Memory leaks are unlikely, as the container is responsible for emptying and destroying the application context if the application is unloaded or the container is shut down.
There are several ways to cache any object. Using the ServletContext is valid as long as you are content managing the life cycle of objects yourself. Check out http://www.opensymphony.com/oscache/ for a widely used implementation of caching. You can configure things like objects lifespans (how long does it live) and even allow caching across a cluster. There are several caching APIs out there and JSR-107 (JCache) is in process (forever now it seems) to standardize this.