Monday, October 26, 2009

Tomcat static file caching

Tomcat caches static files by default.

I think this is probably well-known, but since it was a surprise to a few people that I mentioned it to, I thought I'd discuss it in just slightly more detail.

I was working with a test suite which does the following:
  • Copies a simple text file into Tomcat's webapps/ROOT folder.
  • Fetches the file via HTTP from Tomcat.
  • Copies an altered version of the file over the first file.
  • Fetches the file again via HTTP.
With some regularity, this test was failing, because the second fetch was receiving the first version of the file.

After looking at this a little bit, I realized that Tomcat was caching the file, and was not recognizing that the contents of the file had changed, perhaps because Tomcat may use file timestamps for cache coherency and it's possible to execute the above steps on a fast machine so quickly that the file's timestamp doesn't appear to change.

(The file's size, and checksum, and probably other observable characteristics do change, but perhaps Tomcat's static file cache doesn't notice this?)

At any rate, the fix to these tests is fairly simple: I arranged it so that the tests create a context.xml file in webapps/ROOT/META-INF, with the contents:

<?xml version="1.0" encoding="UTF-8"?>
<context cachingallowed="false">

And now the test seems to reliably retrieve the latest copy of the file when re-fetching it via HTTP.

1 comment: