Guava caches are great, but developing with them can be troublesome.
One solution is wrapping the underlying cache using a simple implementation of the ForwardingCache
class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class DevelopmentForwardingCache<K,V> extends ForwardingCache<K,V> { private Cache<K,V> delegate; private boolean debug; public DevelopmentForwardingCache ( Cache<K,V> delegate ) { this.delegate = delegate; } public DevelopmentForwardingCache<K,V> DEBUG ( ) { this.debug = true; return this; } @Override protected Cache<K, V> delegate ( ) { return this.delegate; } @Override public V get ( K key, Callable<? extends V> valueLoader ) throws ExecutionException { V ret_val = super.get(key, valueLoader); if ( debug ) invalidate(key); return ret_val; } } |
Instead of using a Cache
directly from a CacheBuilder
, you can wrap it with this class and toggle debug mode.
Note: if you’re using a LoadingCache
, you’ll want to derive from the ForwardingLoadingCache
instead and override the get(K key)
and getAll(Iterable<? extends K> keys)
methods as well.