Cache Events in a Terracotta Cluster
Cache events are fired for certain cache operations:
Evictions – An eviction on a client generates an eviction event on that client. An eviction on a Terracotta server fires an event on a random client.
Puts – A put() on a client generates a put event on that client.
Updates – If a cache uses fast restart, then an update on a client generates a put event on that client.
Orphan eviction – An orphan is an element that exists only on the Terracotta Server Array. If an orphan is evicted, an eviction event is fired on a random client.
For information about configuring the scope of cache events in a Terracotta cluster, see "Defining a Distributed Configuration" in the Configuration Guide for BigMemory Max.
Handling Cache Update Events
Caches generate put events whenever elements are put or updated. If it is important for your application to distinguish between puts and updates, check for the existence of the element during put() operations:
if (cache.containsKey(key)) {
cache.put(element);
// Action in the event handler on replace.
} else {
cache.put(element);
// Action in the event handler on new puts.
}
To protect against races, wrap the if block with explicit locks (see
Using Explicit Locking). You can also use the atomic cache methods putIfAbsent() or to check for the existence of an element:
// Returns null if successful or returns the existing (old) element.
if((olde = cache.putIfAbsent(element)) == null) {
// Action in the event handler on new puts.
} else {
cache.replace(old, newElement); // Returns true if successful.
// Action in the event handler on replace.
}
If your code cannot use these approaches (or a similar workaround), you can force update events for cache updates by setting the Terracotta property ehcache.clusteredStore.checkContainsKeyOnPut at the top of the Terracotta configuration file (tc-config.xml by default) before starting the Terracotta Server Array:
<tc-properties>
<property name="ehcache.clusteredStore.checkContainsKeyOnPut" value="true" />
</tc-properties>
Important: | Enabling this property can substantially degrade performance. Clustered caches may not receive notifications for all events, and may receive duplicates of some events. |