|
9. RemovalNotification
Sometimes, you need to take some actions when a record is removed from the cache; so, let’s discuss RemovalNotification.
We can register a RemovalListener to get notifications of a record being removed. We also have access to the cause of the removal – via the getCause() method.
In the following sample, a RemovalNotification is recieved when the forth element in the cache because of its size:- @Test
- public void whenEntryRemovedFromCache_thenNotify() {
- CacheLoader<String, String> loader;
- loader = new CacheLoader<String, String>() {
- @Override
- public String load(final String key) {
- return key.toUpperCase();
- }
- };
- RemovalListener<String, String> listener;
- listener = new RemovalListener<String, String>() {
- @Override
- public void onRemoval(RemovalNotification<String, String> n){
- if (n.wasEvicted()) {
- String cause = n.getCause().name();
- assertEquals(RemovalCause.SIZE.toString(),cause);
- }
- }
- };
- LoadingCache<String, String> cache;
- cache = CacheBuilder.newBuilder()
- .maximumSize(3)
- .removalListener(listener)
- .build(loader);
- cache.getUnchecked("first");
- cache.getUnchecked("second");
- cache.getUnchecked("third");
- cache.getUnchecked("last");
- assertEquals(3, cache.size());
- }
复制代码 |
|