title: Java Web Application: How to implement caching techniques?
body: <p>I am developing a Java web application that bases it behavior through large XML configuration files that are loaded from a web service. As these files are not actually required until a particular section of the application is accessed, they are loaded lazily. When one of these files are required, a query is sent to the webservice to retrieve the corresponding file. As some of the configuration files are likely to be used much, much more often than others I'd like to setup some kind of caching (with maybe a 1 hour expiration time) to avoid requesting the same file over and over.</p>
  
  <p>The files returned by the web service are the same for all users across all sessions. I do not use JSP, JSF or any other fancy framework, just plain servlets.</p>
  
  <p>My question is, what is considered a best practice to implement such a global, static cache within a java Web application? Is a singleton class appropriate, or will there be weird behaviors due to the J2EE containers? Should I expose something somewhere through JNDI? What shall I do so that my cache doesn't get screwed in clustered environments (it's OK, but not necessary, to have one cache per clustered server)? </p>
  
  <p>Given the informations above, Would it be a correct implementation to put an object responsible for caching as a ServletContext attribute?</p>
  
  <p>Note: I do not want to load all of them at startup and be done with it because that would </p>
  
  <p>1). overload the webservice whenever my application starts up<br>
  2). The files might change while my application is running, so I would have to requery them anyway<br>
  3). I would still need a globally accessible cache, so my question still holds</p>
  
  <p>Update: Using a caching proxy (such as squid) may be a good idea, but each request to the webservice will send rather large XML query in the post Data, which may be different each time. Only the web application really knows that two different calls to the webservice are actually equivalent.</p>
  
  <p>Thanks for your help</p>