In a project I was working on recently, we were building up a web page by loading up its template, content hierarchy and other information dynamically. This is a common setup, and a very flexible one since it allows sweeping changes to be made very easily. Unfortunately, this flexibility comes with a cost; pulling everything through EJB calls can give you a speed not unlike that of a slightly stunned tortoise trying to sprint up a treacle covered hill.
One way of mitigating this problem is to use a Facade pattern to load as much as possible with as few calls as possible. However, this is not always the best approach, especially if most of the content is not likely to change very often. In these cases, it’s preferable to store the content at the end where it’s being used, avoiding the remote call completely.
This can be implemented quickly and easily with a Map, but that would leave us with a lot of work to do when it comes to managing the cached content. For example, what if we wanted to make sure that the cache does not continue to fill up indefinitely, or that it gets backed to disk when it goes idle for some time to preserve memory?
Since we were already using Hibernate in the data layer, we were already using a cache at that level in the form of EHCache. It made sense to try and see if it was possible to use this in our controller layer, and it turned out to be extremely elegant to use. Continue reading “Object Caching in Java with EHCache”