17.4 Cache Tags

Caching can improve the responsiveness of a web site significantly. You should cache pages or page sections for a set length of time rather than update the page or section with each request. Cache tags allow pages and sections of pages to be cached. When the page is executed, the cache tag either retrieves the data from its cache or creates the data and caches it. Cache tags can work on a per-user basis, so they are fairly flexible.

An open source cache-tag library, Open Symphony's OSCache, is available from http://www.opensymphony.com/oscache/. Serge Knystautas describes how cache tags can improve performance in a JavaWorld article.[1] You can also use the application server's caching facility, and the session and application objects' caching facilities with ServletContext and HttpSession's getAttribute( )/setAttribute( ) methods. Note that "context" has a much wider scope than "session," so use the HttpSession methods for session-related resources. Using the context can reduce scalability by having resources open over multiple sessions unnecessarily.

[1] Serge Knystautas, "Cache in on faster, more reliable JSPs," JavaWorld, May 2001, http://www.javaworld.com/javaworld/jw-05-2001/jw-0504-cache.html.

Caching trades CPU for memory. This tradeoff must be balanced correctly for optimal performance. Optimal caching needs tuning of timeout settings and other parameters. Cache elements reused in many pages need to be monitored to ensure that they do not become bottlenecks. On highly personalized web sites, page-level caching can result in low cache-hit rates, as each page can be mostly unique to each user. In this case, cache tags are of limited use (perhaps only for small page fragments).