Skip to content

Removal

Ben Manes edited this page Aug 10, 2017 · 13 revisions

Terminology:

  • eviction means removal due to the policy
  • invalidation means manual removal by the caller
  • removal occurs as a consequence of invalidation or eviction

Explicit Removals

At any time, you may explicitly invalidate cache entries rather than waiting for entries to be evicted.

// individual key
cache.invalidate(key)
// bulk keys
cache.invalidateAll(keys)
// all keys
cache.invalidateAll()

Removal Listeners

Cache<Key, Graph> graphs = Caffeine.newBuilder()
    .removalListener((Key key, Graph graph, RemovalCause cause) ->
        System.out.printf("Key %s was removed (%s)%n", key, cause))
    .build();

You may specify a removal listener for your cache to perform some operation when an entry is removed, via Caffeine.removalListener(RemovalListener). The RemovalListener gets passed the key, value, and RemovalCause.

Removal listener operations are executed asynchronously using an Executor. The default executor is ForkJoinPool.commonPool() and can be overridden via Caffeine.executor(Executor). When the operation must be performed synchronously with the removal, use CacheWriter instead.

Note that any exceptions thrown by the RemovalListener are logged (using Logger) and swallowed.

Clone this wiki locally