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