In one of my previous blogs, I gave an overview of Cache Loader+Writer as well as Cache entry listeners. The difference b/w a Cache Loader and Cache create/update entry listener is obvious and their roles are clearly differentiated
- a loader pulls the value from an external source
- populates the cache and
- the respective listener is then invoked
There is no question/doubt on whether one can be substituted for the other
But…
Cache Writer and the Cache create/update entry listener are similar (at least at first glance) – both are invoked when an entry is created/updated in a specific cache
So the obvious Qs are
- why should you use one over the other?
- can we not use cache entry listener to integrate/sync up an external source when the a cache entry is updated/created ?
The important difference is
If the Cache Writer throws an exception, then the entry does not get stored in the cache (think of this as a rollback of sorts). But, in the case of an entry listener, an exception does not effect the value stored in the cache i.e. the created/updated cache entry remains untouched
Cheers!
Hi Abhishek,
CacheEntryEvent extends from Cache.Entry, therefore all the information available in the CacheWriter should be available in a listener too. A listener should be always preferred to CacheWriter to react to The most important difference is that Cache listeners cannot affect cache in any way, even if they throw an exception. On the other hand, if CacheWriter throws an exception, the entry is not stored in the cache. CacheWriter is usually associated with a resource that provides persistence for entries, and is usually coupled with CacheLoader in order to read persisted records. Also, cache must be configured read-through and write-through in order to invoke CacheLoader and CacheWriter respectively.
LikeLike
Thanks Ondrej for the correction! The post has been updated to reflect the same. Guess my mind was already overshadowed with the fact that ‘writers and entry listerners’ cannot be used interchangeably 🙂 But it seems as if one can be used instead of the other (one ‘might’ be more preferable though) bearing in mind the difference you pointed out. Hope that’s the correct interpretation
LikeLike