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:
1public class DevelopmentForwardingCache<K,V> extends ForwardingCache<K,V>
2{
3 private Cache<K,V> delegate;
4
5 private boolean debug;
6
7 public DevelopmentForwardingCache ( Cache<K,V> delegate )
8 {
9 this.delegate = delegate;
10 }
11
12 public DevelopmentForwardingCache<K,V> DEBUG ( )
13 {
14 this.debug = true;
15 return this;
16 }
17
18 @Override
19 protected Cache<K, V> delegate ( )
20 {
21 return this.delegate;
22 }
23
24 @Override
25 public V get ( K key, Callable<? extends V> valueLoader ) throws ExecutionException
26 {
27 V ret_val = super.get(key, valueLoader);
28 if ( debug ) invalidate(key);
29 return ret_val;
30 }
31}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.