Using JCache event listeners + loaders & writers

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

cache-reader-listerner-sequence

Writers

An example where, a new key-value pair is inserted in the cache

 

cache-writer-listerner-sequence

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

 

Cheers!

 

About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Java EE. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s