Yuta HIGUCHI | 41f2ec0 | 2014-10-27 09:54:43 -0700 | [diff] [blame^] | 1 | package org.onlab.onos.store.hz; |
Yuta HIGUCHI | b3b2ac4 | 2014-09-21 23:37:11 -0700 | [diff] [blame] | 2 | |
| 3 | import java.util.concurrent.Callable; |
| 4 | import java.util.concurrent.ExecutionException; |
| 5 | |
| 6 | import com.google.common.base.Optional; |
| 7 | import com.google.common.cache.ForwardingLoadingCache.SimpleForwardingLoadingCache; |
| 8 | import com.google.common.cache.LoadingCache; |
| 9 | |
Yuta HIGUCHI | 951e790 | 2014-09-23 14:45:11 -0700 | [diff] [blame] | 10 | /** |
| 11 | * Wrapper around LoadingCache to handle negative hit scenario. |
| 12 | * <p> |
| 13 | * When the LoadingCache returned Absent, |
| 14 | * this implementation will invalidate the entry immediately to avoid |
| 15 | * caching negative hits. |
| 16 | * |
| 17 | * @param <K> Cache key type |
| 18 | * @param <V> Cache value type. (Optional{@literal <V>}) |
| 19 | */ |
Yuta HIGUCHI | b3b2ac4 | 2014-09-21 23:37:11 -0700 | [diff] [blame] | 20 | public class AbsentInvalidatingLoadingCache<K, V> extends |
| 21 | SimpleForwardingLoadingCache<K, Optional<V>> { |
| 22 | |
Yuta HIGUCHI | 951e790 | 2014-09-23 14:45:11 -0700 | [diff] [blame] | 23 | /** |
| 24 | * Constructor. |
| 25 | * |
| 26 | * @param delegate actual {@link LoadingCache} to delegate loading. |
| 27 | */ |
Yuta HIGUCHI | b3b2ac4 | 2014-09-21 23:37:11 -0700 | [diff] [blame] | 28 | public AbsentInvalidatingLoadingCache(LoadingCache<K, Optional<V>> delegate) { |
| 29 | super(delegate); |
| 30 | } |
| 31 | |
| 32 | @Override |
| 33 | public Optional<V> get(K key) throws ExecutionException { |
| 34 | Optional<V> v = super.get(key); |
| 35 | if (!v.isPresent()) { |
| 36 | invalidate(key); |
| 37 | } |
| 38 | return v; |
| 39 | } |
| 40 | |
| 41 | @Override |
| 42 | public Optional<V> getUnchecked(K key) { |
| 43 | Optional<V> v = super.getUnchecked(key); |
| 44 | if (!v.isPresent()) { |
| 45 | invalidate(key); |
| 46 | } |
| 47 | return v; |
| 48 | } |
| 49 | |
| 50 | @Override |
| 51 | public Optional<V> apply(K key) { |
| 52 | return getUnchecked(key); |
| 53 | } |
| 54 | |
| 55 | @Override |
| 56 | public Optional<V> getIfPresent(Object key) { |
| 57 | Optional<V> v = super.getIfPresent(key); |
| 58 | if (!v.isPresent()) { |
| 59 | invalidate(key); |
| 60 | } |
| 61 | return v; |
| 62 | } |
| 63 | |
| 64 | @Override |
| 65 | public Optional<V> get(K key, Callable<? extends Optional<V>> valueLoader) |
| 66 | throws ExecutionException { |
| 67 | |
| 68 | Optional<V> v = super.get(key, valueLoader); |
| 69 | if (!v.isPresent()) { |
| 70 | invalidate(key); |
| 71 | } |
| 72 | return v; |
| 73 | } |
| 74 | |
| 75 | // TODO should we be also checking getAll, etc. |
| 76 | } |