This blog will:
- Zoom through JCache events, loaders, and writers.
- Look at scenarios when they are used together.
You can download the sample maven project from this GitHub repo. It consists of:
- A simple listener with read-through and write-through examples.
- Some test cases to demonstrate the point.
Reacting to Cache Events and External Store Integration
JCache defines cache event listeners and cache loader/writer features as follows:
- React to cache events: create, update, delete, expiration.
- Triggered as a result of many cache actions (methods on javax.cache.Cache) e.g. get, put, remove, etc.
- Provide transparent ways to integrate the cache with external stores.
- Ability to implement this in the form of a cache loader (read from an external source if the key is not present in the cache) and cache writer (updates the external store in case of new entry, update, or delete)
- Caches which implement this are also known as read through and/or write through
When They Are Used Together…
Let’s look at the sequence of events when everything works in tandem:
An example where a key (which did not previously exist) is looked up from the cache is:
An example where a new key-value pair is inserted in the cache looks like this:
Things work similarly in a case of updated or removed cache entries.
A Few Things Worth Noting
- Event listeners are synchronous: They are invoked in the same thread as the caller (e.g. the one invoking the get operation on the cache). Thus, that value can’t be returned to a caller while the event listener is still executing
- Exceptions during cache entry listener invocation have no impact on the cache itself since it (the cache) has already undergone changes (create/update/delete)
- One should not invoke cache operations from event listener callbacks, loader, or writer implementations – check spec page 133 (#10).