b57ac7471947cda48c17397ad51260f7b80ba892
[groupbasedpolicy.git] / sxp-mapper / src / main / java / org / opendaylight / groupbasedpolicy / sxp / mapper / impl / dao / SimpleCachedDaoImpl.java
1 /**
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.groupbasedpolicy.sxp.mapper.impl.dao;
9
10 import com.google.common.base.Optional;
11 import com.google.common.collect.Iterables;
12 import java.util.concurrent.ConcurrentHashMap;
13 import java.util.concurrent.ConcurrentMap;
14 import javax.annotation.Nonnull;
15 import javax.annotation.Nullable;
16 import org.opendaylight.groupbasedpolicy.sxp.mapper.api.SimpleCachedDao;
17 import org.opendaylight.yangtools.yang.binding.DataObject;
18
19 /**
20  * Purpose: generic implementation of {@link SimpleCachedDao}
21  */
22 public class SimpleCachedDaoImpl<K, V extends DataObject> implements SimpleCachedDao<K, V> {
23
24     private final ConcurrentMap<K, V> cache;
25
26     public SimpleCachedDaoImpl() {
27         cache = new ConcurrentHashMap<>();
28     }
29
30     @Override
31     public V update(@Nonnull final K key, @Nullable final V value) {
32         final V previousValue;
33         if (value != null) {
34             previousValue = cache.put(key, value);
35         } else {
36             previousValue = cache.remove(key);
37         }
38
39         return previousValue;
40     }
41
42     @Override
43     public Optional<V> find(@Nonnull final K key) {
44         return Optional.fromNullable(cache.get(key));
45     }
46
47     @Override
48     public void invalidateCache() {
49         cache.clear();
50     }
51
52     @Override
53     public boolean isEmpty() {
54         return cache.isEmpty();
55     }
56
57     @Override
58     public Iterable<V> values() {
59         return Iterables.unmodifiableIterable(cache.values());
60     }
61 }