Posts tagged ‘visitior’


In this post I’ll revisit memoization topic described some time ago in this post, with slight modification:

  • playground – ejb3.1 compilant container
  • resolve key-generation problem only tackled in previous installment.


I want to be able to cache calls to my method in a way that is transparent with configurable cache duration.

Solution description

EJB3 Interceptor

In ejb3+ environment, the ability to put transparent wrapper to a method call is called interceptor – it lets you access target method as well as parameters. It’s even possible to communicate with your target using context but we’re not going to need it in this call.

So a CachingInterceptor aggregates both CacheManager as well as KeyGeneratorEJB3 and as you can see both are just interfaces meant to be used with any caching solution and any key generation algorigth of you choice. Currently CacheManger is a generic interface that lets user impose limitations on the type of keys used for cache.

Currently our cache implementation uses EHCache which gives user ability to do configuration in a separate file, so we’re going to stick with that.

As you can see there are different patterns for ehcache integration. We’re going to use cache-aside because this one is the easiest way to replace ehcache with any other caching mechanism.

KeyGeneratorEJB3 defines just one method that should be used as entry point for interaction with CachingInterceptor.

Cache key generation

As mentioned previously key generation was not taken under serious consideration in my previous entry  – that’s why I ended up with semantical toString which was easy way to go – but in case there’s no access to the underlying code might be an issue.

So this time I decided to use a slightly modified Visitor pattern* – I want to have a stateless bean so my keygenrator is supposed to return a value from its visit method (named generate in my case) which should be used as a key. This implies that all accept methods (named generate in my case) need to return string as well, which makes things not so transparent.


As you can see in this post EJB3 environment gives you even more flexibility to use a caching middle-man and with improved key-generation policy it’s finally in a right place.


*I did not put any hyperlink so it wont confuse anyone looking for a valid visitor pattern.