blob: 7e575b01c7ee220fcb32ef412927e8dcd5c19957 [file] [log] [blame]
Madan Jampanid3520102015-08-14 11:06:03 -07001/*
2 * Copyright 2015 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 */
Madan Jampani3d6a2f62015-08-12 07:19:07 -070016package org.onosproject.store.consistent.impl;
17
18import java.util.concurrent.CompletableFuture;
19
20import org.onosproject.core.ApplicationId;
21import org.onosproject.store.service.Serializer;
22import org.onosproject.store.service.Versioned;
23
24import com.google.common.cache.CacheBuilder;
25import com.google.common.cache.CacheLoader;
26import com.google.common.cache.LoadingCache;
27
28/**
29 * Extension of DefaultAsyncConsistentMap that provides a weaker read consistency
30 * guarantee in return for better read performance.
31 *
32 * @param <K> key type
33 * @param <V> value type
34 */
35public class AsyncCachingConsistentMap<K, V> extends DefaultAsyncConsistentMap<K, V> {
36
37 private final LoadingCache<K, CompletableFuture<Versioned<V>>> cache =
38 CacheBuilder.newBuilder()
39 .maximumSize(10000) // TODO: make configurable
40 .build(new CacheLoader<K, CompletableFuture<Versioned<V>>>() {
41 @Override
42 public CompletableFuture<Versioned<V>> load(K key)
43 throws Exception {
44 return AsyncCachingConsistentMap.super.get(key);
45 }
46 });
47
48 public AsyncCachingConsistentMap(String name,
49 ApplicationId applicationId,
50 Database database,
51 Serializer serializer,
52 boolean readOnly,
53 boolean purgeOnUninstall,
54 boolean meteringEnabled) {
55 super(name, applicationId, database, serializer, readOnly, purgeOnUninstall, meteringEnabled);
56 addListener(event -> cache.invalidate(event.key()));
57 }
58
59 @Override
60 public CompletableFuture<Versioned<V>> get(K key) {
61 CompletableFuture<Versioned<V>> cachedValue = cache.getIfPresent(key);
62 if (cachedValue != null) {
63 if (cachedValue.isCompletedExceptionally()) {
64 cache.invalidate(key);
65 } else {
66 return cachedValue;
67 }
68 }
69 return cache.getUnchecked(key);
70 }
71}