Merge "Added tests for yang.model.util"
[yangtools.git] / common / object-cache-api / src / main / java / org / opendaylight / yangtools / objcache / spi / AbstractObjectCache.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.spi;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.FinalizableReferenceQueue;
12 import com.google.common.base.FinalizableSoftReference;
13 import com.google.common.base.Preconditions;
14 import com.google.common.cache.Cache;
15 import java.util.concurrent.Callable;
16 import java.util.concurrent.ExecutionException;
17 import org.opendaylight.yangtools.concepts.ProductAwareBuilder;
18 import org.opendaylight.yangtools.objcache.ObjectCache;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 /**
23  * Abstract object cache implementation. This implementation takes care
24  * of interacting with the user and manages interaction with the Garbage
25  * Collector (via soft references). Subclasses are expected to provide
26  * a backing {@link Cache} instance and provide the
27  */
28 public abstract class AbstractObjectCache implements ObjectCache {
29     /**
30      * Key used when looking up a ProductAwareBuilder product. We assume
31      * the builder is not being modified for the duration of the lookup,
32      * anything else is the user's fault.
33      */
34     @VisibleForTesting
35     static final class BuilderKey {
36         private final ProductAwareBuilder<?> builder;
37
38         private BuilderKey(final ProductAwareBuilder<?> builder) {
39             this.builder = Preconditions.checkNotNull(builder);
40         }
41
42         @Override
43         public int hashCode() {
44             return builder.productHashCode();
45         }
46
47         @Override
48         public boolean equals(Object obj) {
49             /*
50              * We can tolerate null objects coming our way, but we need
51              * to be on the lookout for WeakKeys, as we cannot pass them
52              * directly to productEquals().
53              */
54             if (obj instanceof SoftKey) {
55                 obj = ((SoftKey<?>)obj).get();
56             }
57
58             return builder.productEquals(obj);
59         }
60     }
61
62     /**
63      * Key used in the underlying map. It is essentially a soft reference, with
64      * slightly special properties.
65      *
66      * It acts as a proxy for the object it refers to and essentially delegates
67      * to it. There are three exceptions here:
68      *
69      * 1) This key needs to have a cached hash code. The requirement is that the
70      *    key needs to be able to look itself up after the reference to the object
71      *    has been cleared (and thus we can no longer look it up from there). One
72      *    typical container where we are stored are HashMaps -- and they need it
73      *    to be constant.
74      * 2) This key does not tolerate checks to see if its equal to null. While we
75      *    could return false, we want to catch offenders who try to store nulls
76      *    in the cache.
77      * 3) This key inverts the check for equality, e.g. it calls equals() on the
78      *    object which was passed to its equals(). Instead of supplying itself,
79      *    it supplies the referent. If the soft reference is cleared, such check
80      *    will return false, which is fine as it prevents normal lookup from
81      *    seeing the cleared key. Removal is handled by the explicit identity
82      *    check.
83      */
84     protected abstract static class SoftKey<T> extends FinalizableSoftReference<T> {
85         private final int hashCode;
86
87         public SoftKey(final T referent, final FinalizableReferenceQueue q) {
88             super(Preconditions.checkNotNull(referent), q);
89             hashCode = referent.hashCode();
90         }
91
92         @Override
93         public boolean equals(final Object obj) {
94             if (obj == null) {
95                 return false;
96             }
97
98             // Order is important: we do not want to call equals() on ourselves!
99             return this == obj || obj.equals(get());
100         }
101
102         @Override
103         public int hashCode() {
104             return hashCode;
105         }
106     }
107
108     private static final Logger LOG = LoggerFactory.getLogger(AbstractObjectCache.class);
109     private final FinalizableReferenceQueue queue;
110     private final Cache<SoftKey<?>, Object> cache;
111
112     protected AbstractObjectCache(final Cache<SoftKey<?>, Object> cache, final FinalizableReferenceQueue queue) {
113         this.queue = Preconditions.checkNotNull(queue);
114         this.cache = Preconditions.checkNotNull(cache);
115     }
116
117     protected <T> SoftKey<T> createSoftKey(final T object) {
118         /*
119          * This may look like a race (having a soft reference and not have
120          * it in the cache). In fact this is protected by the fact we still
121          * have a strong reference on the object in our arguments and that
122          * reference survives past method return since we return it.
123          */
124         return new SoftKey<T>(object, queue) {
125             @Override
126             public void finalizeReferent() {
127                 /*
128                  * NOTE: while it may be tempting to add "object" into this
129                  *       trace message, do not ever do that: it would retain
130                  *       a strong reference, preventing collection.
131                  */
132                 LOG.trace("Invalidating key {}", this);
133                 cache.invalidate(this);
134             }
135         };
136     }
137
138     @Override
139     public final <B extends ProductAwareBuilder<P>, P> P getProduct(final B builder) {
140         throw new UnsupportedOperationException();
141 //        LOG.debug("Looking up product for {}", builder);
142 //
143 //        @SuppressWarnings("unchecked")
144 //        final P ret = (P) cache.getIfPresent(new BuilderKey(builder));
145 //        return ret == null ? put(Preconditions.checkNotNull(builder.toInstance())) : ret;
146     }
147
148     @Override
149     @SuppressWarnings("unchecked")
150     public final <T> T getReference(final T object) {
151         LOG.debug("Looking up reference for {}", object);
152         if (object == null) {
153             return null;
154         }
155
156         final SoftKey<T> key = createSoftKey(object);
157         try {
158             return (T) cache.get(key, new Callable<T>() {
159                 @Override
160                 public T call() {
161                     return object;
162                 }
163             });
164         } catch (ExecutionException e) {
165             throw new IllegalStateException("Failed to load value", e);
166         }
167     }
168 }