Madan Jampani | 3d6a2f6 | 2015-08-12 07:19:07 -0700 | [diff] [blame^] | 1 | package org.onosproject.store.consistent.impl; |
| 2 | |
| 3 | import java.util.concurrent.CompletableFuture; |
| 4 | |
| 5 | import org.onosproject.core.ApplicationId; |
| 6 | import org.onosproject.store.service.Serializer; |
| 7 | import org.onosproject.store.service.Versioned; |
| 8 | |
| 9 | import com.google.common.cache.CacheBuilder; |
| 10 | import com.google.common.cache.CacheLoader; |
| 11 | import 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 | */ |
| 20 | public 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 | } |