2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.objcache.spi;
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;
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
28 public abstract class AbstractObjectCache implements ObjectCache {
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.
35 static final class BuilderKey {
36 private final ProductAwareBuilder<?> builder;
38 private BuilderKey(final ProductAwareBuilder<?> builder) {
39 this.builder = Preconditions.checkNotNull(builder);
43 public int hashCode() {
44 return builder.productHashCode();
48 public boolean equals(Object obj) {
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().
54 if (obj instanceof SoftKey) {
55 obj = ((SoftKey<?>)obj).get();
58 return builder.productEquals(obj);
63 * Key used in the underlying map. It is essentially a soft reference, with
64 * slightly special properties.
66 * It acts as a proxy for the object it refers to and essentially delegates
67 * to it. There are three exceptions here:
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
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
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
84 protected abstract static class SoftKey<T> extends FinalizableSoftReference<T> {
85 private final int hashCode;
87 public SoftKey(final T referent, final FinalizableReferenceQueue queue) {
88 super(Preconditions.checkNotNull(referent), queue);
89 hashCode = referent.hashCode();
93 public boolean equals(final Object obj) {
98 // Order is important: we do not want to call equals() on ourselves!
99 return this == obj || obj.equals(get());
103 public int hashCode() {
108 private static final Logger LOG = LoggerFactory.getLogger(AbstractObjectCache.class);
109 private final FinalizableReferenceQueue queue;
110 private final Cache<SoftKey<?>, Object> cache;
112 protected AbstractObjectCache(final Cache<SoftKey<?>, Object> cache, final FinalizableReferenceQueue queue) {
113 this.queue = Preconditions.checkNotNull(queue);
114 this.cache = Preconditions.checkNotNull(cache);
117 protected <T> SoftKey<T> createSoftKey(final T object) {
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.
124 return new SoftKey<T>(object, queue) {
126 public void finalizeReferent() {
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.
132 LOG.trace("Invalidating key {}", this);
133 cache.invalidate(this);
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);
143 // @SuppressWarnings("unchecked")
144 // final P ret = (P) cache.getIfPresent(new BuilderKey(builder));
145 // return ret == null ? put(Preconditions.checkNotNull(builder.toInstance())) : ret;
149 @SuppressWarnings("unchecked")
150 public final <T> T getReference(final T object) {
151 LOG.debug("Looking up reference for {}", object);
152 if (object == null) {
156 final SoftKey<T> key = createSoftKey(object);
158 return (T) cache.get(key, new Callable<T>() {
164 } catch (ExecutionException e) {
165 throw new IllegalStateException("Failed to load value", e);