Terracotta 10.7 | Ehcache API Developer Guide | Cache Event Listeners | Introduction
 
Introduction
Cache listeners allow implementers to register callback methods that will be executed when a cache event occurs.
Listeners are registered at the cache level - and therefore only receive events for caches that they have been registered with.

CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration =
CacheEventListenerConfigurationBuilder
.newEventListenerConfiguration(new ListenerObject(), EventType.CREATED,
EventType.UPDATED) // 1
.unordered().asynchronous(); // 2

final CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("foo",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class,
String.class, ResourcePoolsBuilder.heap(10))
.add(cacheEventListenerConfiguration) // 3
).build(true);

final Cache<String, String> cache = manager.getCache("foo", String.class, String.class);
cache.put("Hello", "World"); // 4
cache.put("Hello", "Everyone"); // 5
cache.remove("Hello"); // 6
1
Create a CacheEventListenerConfiguration using the builder indicating the listener and the events to receive (in this case create and update events)
2
Optionally indicate the delivery mode - defaults are asynchronous and un-ordered (for performance reasons)
3
Pass the configuration of the listener into the cache configuration
4
You will be notified on creation
5
And on update
6
But not on removal, because it wasn't included at step 1
Created, updated, and removed events are triggered by user execution of mutative methods as outlined in the table below. Eviction and expiration events can be triggered by both internal processes and by user execution of methods targeting both related and unrelated keys within the cache.
Cache entry event firing behaviors for mutative methods
input
operation
output
event {key, old-value, new-value}
{}
put(K, V)
{K, V}
created {K, null, V}
{K, V1}
put(K, V2)
{K, V2}
updated {K, V1, V2}
{}
put(K, V) [immediately expired]
{}
none
{K, V1}
put(K, V2) [immediately expired]
{}
none
{}
putIfAbsent(K, V)
{K, V}
created {K, null, V}
{}
putIfAbsent(K, V) [immediately expired]
{}
none
{K, V1}
replace(K, V2)
{K, V2}
updated {K, V1, V2}
{K, V1}
replace(K, V2) [immediately expired]
{}
none
{K, V1}
replace(K, V1, V2)
{K, V2}
updated {K, V1, V2}
{K, V1}
replace(K, V1, V2) [immediately expired]
{}
no events
{K, V}
remove(K)
{}
removed {K, V, null}
Note:Ehcache provides an abstract class CacheEventAdapter for convenient implementation of event listeners when you are interested only on specific events.