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