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