2 * Copyright 2015 Open Networking Laboratory
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onosproject.store.consistent.impl;
18 import java.util.concurrent.CompletableFuture;
20 import org.onosproject.core.ApplicationId;
21 import org.onosproject.store.service.Serializer;
22 import org.onosproject.store.service.Versioned;
24 import com.google.common.cache.CacheBuilder;
25 import com.google.common.cache.CacheLoader;
26 import com.google.common.cache.LoadingCache;
29 * Extension of DefaultAsyncConsistentMap that provides a weaker read consistency
30 * guarantee in return for better read performance.
33 * @param <V> value type
35 public class AsyncCachingConsistentMap<K, V> extends DefaultAsyncConsistentMap<K, V> {
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>>>() {
42 public CompletableFuture<Versioned<V>> load(K key)
44 return AsyncCachingConsistentMap.super.get(key);
48 public AsyncCachingConsistentMap(String name,
49 ApplicationId applicationId,
51 Serializer serializer,
53 boolean purgeOnUninstall,
54 boolean meteringEnabled) {
55 super(name, applicationId, database, serializer, readOnly, purgeOnUninstall, meteringEnabled);
56 addListener(event -> cache.invalidate(event.key()));
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);
69 return cache.getUnchecked(key);