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
- simple Listener, read through, write through examples
- along with 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
Event listeners
- react to cache events – create, update, delete, expiry
- triggered as a result of many Cache actions (methods on javax.cache.Cache) e.g. get, put, remove etc.
Integrations
- Provide transparent way to integrate the cache with external store
- Ability to implement this in form of Cache Loader (read from external source if key is not present in cache) and Cache Writer (update 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
Loaders
An example where a key (which did not previously exist) is looked up from the cache
Writers
An example where, a new key-value pair is inserted in the cache
Things work similarly in case of updated or removed cache entries
Its worth noting that
- Event listeners are Synchronous: i.e. they are invoked in same thread as the caller (e.g. the one invoking the get operation on the cache). Thus, that value can’t be returned to caller while event listener is still executing
- Exceptions during cache entry listener invocation has 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, loaders or writers implementations – check spec page 133 (#10)
Additional reading
- JCache specification
- JSR 107 Github repo
- JCache DZone refcard
- Previous blogs related to JCache
Cheers!