blob: 8164467bac5982bbdcbe94e1315bc9133f3f73df [file] [log] [blame]
Yuta HIGUCHI41f2ec02014-10-27 09:54:43 -07001package org.onlab.onos.store.hz;
Yuta HIGUCHIb3b2ac42014-09-21 23:37:11 -07002
3import java.util.concurrent.Callable;
4import java.util.concurrent.ExecutionException;
5
6import com.google.common.base.Optional;
7import com.google.common.cache.ForwardingLoadingCache.SimpleForwardingLoadingCache;
8import com.google.common.cache.LoadingCache;
9
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070010/**
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 HIGUCHIb3b2ac42014-09-21 23:37:11 -070020public class AbsentInvalidatingLoadingCache<K, V> extends
21 SimpleForwardingLoadingCache<K, Optional<V>> {
22
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070023 /**
24 * Constructor.
25 *
26 * @param delegate actual {@link LoadingCache} to delegate loading.
27 */
Yuta HIGUCHIb3b2ac42014-09-21 23:37:11 -070028 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}