f2bc895676b1fc38a8f36b9def2243271f790f7c
[genius.git] / mdsalutil / mdsalutil-api / src / main / java / org / opendaylight / genius / utils / cache / CacheUtil.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. 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.genius.utils.cache;
9
10 import java.util.concurrent.ConcurrentHashMap;
11 import java.util.concurrent.ConcurrentMap;
12
13 /**
14  * Cache wannabe.
15  *
16  * <p>This class wanted to be Cache when it was grown up. Currently it's actually just
17  * a nested ConcurrentMap, and thus has fairly limited real value.
18  *
19  * <p>The usage of static methods here, instead of an (OSGi) "service"
20  * (dependency inject-able in tests!) makes it impossible to easily properly
21  * use code relying on this in component tests (as there would be no automatic
22  * reset between tests; you would have to manually {@link #destroyCache(String)}
23  * {@literal @}Before each test).
24  *
25  * <p>This class' "static" Singleton doesn't play nice with OSGi e.g. for hot reload.
26  *
27  * <p>This class' (necessary) use &lt;?&gt; generics causes {@literal @}SuppressWarnings("unchecked") when used.
28  *
29  * <p>Perhaps you would like to use <a href="https://github.com/google/guava/wiki/CachesExplained">
30  * Google Guava's simple Caches</a>, if not a full blown JSR 107 javax.cache (JCache) implementation,
31  * such as <a href="http://infinispan.org">Infinispan</a> or <a href="http://www.ehcache.org">Ehcache</a>,
32  * instead of this class?
33  *
34  * @deprecated We now recommend you simply use your own {@code new ConcurrentHashMap<>()} instead.
35  *
36  * @author unascribed (Ericsson India?) - original code
37  * @author Michael Vorburger.ch - JavaDoc
38  */
39 @Deprecated
40 public final class CacheUtil {
41
42     // package local instead of private for CacheTestUtil
43     static final ConcurrentMap<String, ConcurrentMap<?, ?>> MAP_OF_MAP = new ConcurrentHashMap<>();
44
45     private CacheUtil() {
46
47     }
48
49     public static ConcurrentMap<?, ?> getCache(String cacheName) {
50         return MAP_OF_MAP.get(cacheName);
51     }
52
53     public static void createCache(String cacheName) {
54         MAP_OF_MAP.computeIfAbsent(cacheName, k -> new ConcurrentHashMap<>());
55     }
56
57     public static boolean isCacheValid(String cacheName) {
58         return MAP_OF_MAP.containsKey(cacheName);
59     }
60
61     public static void destroyCache(String cacheName) {
62         MAP_OF_MAP.remove(cacheName);
63     }
64 }