Java 8 here. Is there any way with the Caffeine caching framework (or any other JSR-107 compatible framework for that matter) to be notified when a record is evicted out of the cache?
Maybe some kind of EvictionEventListener
or something?
public class MyEvictionListener implements EvictionEventListener<String> {
@Override
public void onEvictionEvent(EvictionEvent eviction, String key) {
// Now I have access to the String "key" that was evicted and
// some information surrounding the eviction and I can do
// whatever I want with this information....
}
}
Is there anything like this in Caffeine, Guava, Hazelcast, (basically "JVM cache land") etc.?
Eviction by time or by space ?
In JSR107 you must get an event for the former and must not for the latter. See section 8.4 of the spec "8.4. Invocation of Listeners".
All JCache implementations must support eviction by time, and you would be aware of this via javax.cache.event.CacheEntryExpiredListener<K, V>
. Expiry can be eager or lazy according to the implementation, items will not necessary disappear at the point at which their time limit occurs.
JCache allows for implementations to extend this with space based.
With Hazelcast you could do this
<eviction size="50" max-size-policy="ENTRY_COUNT" eviction-policy="LRU"/>
to discard items from a cache according to a configurable space threshold. However, as this is implementation dependent, there's no JCache event for it.
JCache's EXPIRED event is produced by the system, cannot be directly triggered by the user. The REMOVED event is only for user initiated actions, such as cache.remove(k)
. The other two kinds CREATED and UPDATED won't help here either.