blob: dddd1287eb8a5e81418e3d80df2767fd413627a5 [file] [log] [blame]
Yuta HIGUCHI951e7902014-09-23 14:45:11 -07001package org.onlab.onos.store.impl;
2
3import static com.google.common.base.Preconditions.checkNotNull;
4
tom0755a362014-09-24 11:54:43 -07005import org.onlab.onos.store.common.StoreService;
Yuta HIGUCHI951e7902014-09-23 14:45:11 -07006
7import com.google.common.base.Optional;
8import com.google.common.cache.CacheLoader;
9import com.hazelcast.core.IMap;
10
11/**
12 * CacheLoader to wrap Map value with Optional,
13 * to handle negative hit on underlying IMap.
14 *
15 * @param <K> IMap key type after deserialization
16 * @param <V> IMap value type after deserialization
17 */
18public final class OptionalCacheLoader<K, V> extends
19 CacheLoader<K, Optional<V>> {
20
21 private final StoreService storeService;
22 private IMap<byte[], byte[]> rawMap;
23
24 /**
25 * Constructor.
26 *
27 * @param storeService to use for serialization
28 * @param rawMap underlying IMap
29 */
30 public OptionalCacheLoader(StoreService storeService, IMap<byte[], byte[]> rawMap) {
31 this.storeService = checkNotNull(storeService);
32 this.rawMap = checkNotNull(rawMap);
33 }
34
35 @Override
36 public Optional<V> load(K key) throws Exception {
37 byte[] keyBytes = storeService.serialize(key);
38 byte[] valBytes = rawMap.get(keyBytes);
39 if (valBytes == null) {
40 return Optional.absent();
41 }
42 V dev = storeService.deserialize(valBytes);
43 return Optional.of(dev);
44 }
45}