Skip to content
Ben Manes edited this page Jun 12, 2015 · 35 revisions

CacheWriter is in early development and not yet fully integrated. This draft documents the expected usage.

Write-through and Write-back

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
    .writer(new CacheWriter<>() {
      @Override public void write(Key key, Graph graph) {
        // write to storage or secondary cache
      }
      @Override public void delete(Key key, Graph graph, RemovalCause cause) {
        if (!cause.isEvicted()) {
          // delete from storage or secondary cache
        }
      }
    }).build(key -> createExpensiveGraph(key));

Write-through updates the cache and external resource as a single atomic cache operation.

Write-back updates the cache and asynchronously updates the resource.

Victim cache

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
    .writer(new CacheWriter<>() {
      @Override public void write(Key key, Graph graph) {
        // delete from secondary cache
      }
      @Override public void delete(Key key, Graph graph, RemovalCause cause) {
        if (cause.isEvicted()) {
          // write to secondary cache
        }
      }
    }).build(key -> createExpensiveGraph(key));

A victim cache is a secondary cache that stores the entries that were evicted. While this can be implemented using a RemovalListener, there exists a race condition due to the listener being called after the cache operation completes.

Clone this wiki locally