blob: 63c505f8cb4ad4bdbb444f52738719d460d40ebf [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Yuta HIGUCHI41f2ec02014-10-27 09:54:43 -070016package org.onlab.onos.store.hz;
Yuta HIGUCHIb3b2ac42014-09-21 23:37:11 -070017
18import java.util.concurrent.Callable;
19import java.util.concurrent.ExecutionException;
20
21import com.google.common.base.Optional;
22import com.google.common.cache.ForwardingLoadingCache.SimpleForwardingLoadingCache;
23import com.google.common.cache.LoadingCache;
24
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070025/**
26 * Wrapper around LoadingCache to handle negative hit scenario.
27 * <p>
28 * When the LoadingCache returned Absent,
29 * this implementation will invalidate the entry immediately to avoid
30 * caching negative hits.
31 *
32 * @param <K> Cache key type
33 * @param <V> Cache value type. (Optional{@literal <V>})
34 */
Yuta HIGUCHIb3b2ac42014-09-21 23:37:11 -070035public class AbsentInvalidatingLoadingCache<K, V> extends
36 SimpleForwardingLoadingCache<K, Optional<V>> {
37
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070038 /**
39 * Constructor.
40 *
41 * @param delegate actual {@link LoadingCache} to delegate loading.
42 */
Yuta HIGUCHIb3b2ac42014-09-21 23:37:11 -070043 public AbsentInvalidatingLoadingCache(LoadingCache<K, Optional<V>> delegate) {
44 super(delegate);
45 }
46
47 @Override
48 public Optional<V> get(K key) throws ExecutionException {
49 Optional<V> v = super.get(key);
50 if (!v.isPresent()) {
51 invalidate(key);
52 }
53 return v;
54 }
55
56 @Override
57 public Optional<V> getUnchecked(K key) {
58 Optional<V> v = super.getUnchecked(key);
59 if (!v.isPresent()) {
60 invalidate(key);
61 }
62 return v;
63 }
64
65 @Override
66 public Optional<V> apply(K key) {
67 return getUnchecked(key);
68 }
69
70 @Override
71 public Optional<V> getIfPresent(Object key) {
72 Optional<V> v = super.getIfPresent(key);
73 if (!v.isPresent()) {
74 invalidate(key);
75 }
76 return v;
77 }
78
79 @Override
80 public Optional<V> get(K key, Callable<? extends Optional<V>> valueLoader)
81 throws ExecutionException {
82
83 Optional<V> v = super.get(key, valueLoader);
84 if (!v.isPresent()) {
85 invalidate(key);
86 }
87 return v;
88 }
89
90 // TODO should we be also checking getAll, etc.
91}