BUG-994: improve object cache
[yangtools.git] / common / object-cache-api / src / main / java / org / opendaylight / yangtools / objcache / ObjectCacheFactory.java
1 /*
2  * Copyright (c) 2014 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.yangtools.objcache;
9
10 import javax.annotation.Nonnull;
11
12 import org.opendaylight.yangtools.objcache.impl.StaticObjectCacheBinder;
13 import org.opendaylight.yangtools.objcache.spi.IObjectCacheFactory;
14 import org.opendaylight.yangtools.objcache.spi.NoopObjectCacheBinder;
15
16 import com.google.common.base.Preconditions;
17
18 /**
19  * Point of entry for acquiring an {@link ObjectCache} instance.
20  */
21 public final class ObjectCacheFactory {
22     private static IObjectCacheFactory FACTORY;
23
24     private static synchronized IObjectCacheFactory initialize() {
25         // Double-check under lock
26         if (FACTORY != null) {
27             return FACTORY;
28         }
29
30         IObjectCacheFactory f;
31         try {
32             f = StaticObjectCacheBinder.getInstance().getProductCacheFactory();
33             FACTORY = f;
34         } catch (NoClassDefFoundError e) {
35             f = NoopObjectCacheBinder.INSTANCE.getProductCacheFactory();
36         }
37
38         return f;
39     }
40
41     public static synchronized void reset() {
42         FACTORY = null;
43     }
44
45     /**
46      * Get an ObjectCache for caching a particular object class. Note
47      * that it may be shared for multiple classes.
48      *
49      * @param objClass Class of objects which are to be cached
50      * @return Object cache instance.
51      */
52     public static ObjectCache getObjectCache(@Nonnull final Class<?> objClass) {
53         IObjectCacheFactory f = FACTORY;
54         if (f == null) {
55             f = initialize();
56         }
57
58         return f.getObjectCache(Preconditions.checkNotNull(objClass));
59     }
60 }