1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/rt/emul/compact/src/main/java/java/lang/ClassValue.java Sun Aug 10 05:55:55 2014 +0200
1.3 @@ -0,0 +1,760 @@
1.4 +/*
1.5 + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1.7 + *
1.8 + * This code is free software; you can redistribute it and/or modify it
1.9 + * under the terms of the GNU General Public License version 2 only, as
1.10 + * published by the Free Software Foundation. Oracle designates this
1.11 + * particular file as subject to the "Classpath" exception as provided
1.12 + * by Oracle in the LICENSE file that accompanied this code.
1.13 + *
1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1.17 + * version 2 for more details (a copy is included in the LICENSE file that
1.18 + * accompanied this code).
1.19 + *
1.20 + * You should have received a copy of the GNU General Public License version
1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1.23 + *
1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1.25 + * or visit www.oracle.com if you need additional information or have any
1.26 + * questions.
1.27 + */
1.28 +
1.29 +package java.lang;
1.30 +
1.31 +import java.lang.ClassValue.ClassValueMap;
1.32 +import java.util.WeakHashMap;
1.33 +import java.lang.ref.WeakReference;
1.34 +import java.util.concurrent.atomic.AtomicInteger;
1.35 +
1.36 +import static java.lang.ClassValue.ClassValueMap.probeHomeLocation;
1.37 +import static java.lang.ClassValue.ClassValueMap.probeBackupLocations;
1.38 +
1.39 +/**
1.40 + * Lazily associate a computed value with (potentially) every type.
1.41 + * For example, if a dynamic language needs to construct a message dispatch
1.42 + * table for each class encountered at a message send call site,
1.43 + * it can use a {@code ClassValue} to cache information needed to
1.44 + * perform the message send quickly, for each class encountered.
1.45 + * @author John Rose, JSR 292 EG
1.46 + * @since 1.7
1.47 + */
1.48 +public abstract class ClassValue<T> {
1.49 + /**
1.50 + * Sole constructor. (For invocation by subclass constructors, typically
1.51 + * implicit.)
1.52 + */
1.53 + protected ClassValue() {
1.54 + }
1.55 +
1.56 + /**
1.57 + * Computes the given class's derived value for this {@code ClassValue}.
1.58 + * <p>
1.59 + * This method will be invoked within the first thread that accesses
1.60 + * the value with the {@link #get get} method.
1.61 + * <p>
1.62 + * Normally, this method is invoked at most once per class,
1.63 + * but it may be invoked again if there has been a call to
1.64 + * {@link #remove remove}.
1.65 + * <p>
1.66 + * If this method throws an exception, the corresponding call to {@code get}
1.67 + * will terminate abnormally with that exception, and no class value will be recorded.
1.68 + *
1.69 + * @param type the type whose class value must be computed
1.70 + * @return the newly computed value associated with this {@code ClassValue}, for the given class or interface
1.71 + * @see #get
1.72 + * @see #remove
1.73 + */
1.74 + protected abstract T computeValue(Class<?> type);
1.75 +
1.76 + /**
1.77 + * Returns the value for the given class.
1.78 + * If no value has yet been computed, it is obtained by
1.79 + * an invocation of the {@link #computeValue computeValue} method.
1.80 + * <p>
1.81 + * The actual installation of the value on the class
1.82 + * is performed atomically.
1.83 + * At that point, if several racing threads have
1.84 + * computed values, one is chosen, and returned to
1.85 + * all the racing threads.
1.86 + * <p>
1.87 + * The {@code type} parameter is typically a class, but it may be any type,
1.88 + * such as an interface, a primitive type (like {@code int.class}), or {@code void.class}.
1.89 + * <p>
1.90 + * In the absence of {@code remove} calls, a class value has a simple
1.91 + * state diagram: uninitialized and initialized.
1.92 + * When {@code remove} calls are made,
1.93 + * the rules for value observation are more complex.
1.94 + * See the documentation for {@link #remove remove} for more information.
1.95 + *
1.96 + * @param type the type whose class value must be computed or retrieved
1.97 + * @return the current value associated with this {@code ClassValue}, for the given class or interface
1.98 + * @throws NullPointerException if the argument is null
1.99 + * @see #remove
1.100 + * @see #computeValue
1.101 + */
1.102 + public T get(Class<?> type) {
1.103 + // non-racing this.hashCodeForCache : final int
1.104 + Entry<?>[] cache;
1.105 + Entry<T> e = probeHomeLocation(cache = getCacheCarefully(type), this);
1.106 + // racing e : current value <=> stale value from current cache or from stale cache
1.107 + // invariant: e is null or an Entry with readable Entry.version and Entry.value
1.108 + if (match(e))
1.109 + // invariant: No false positive matches. False negatives are OK if rare.
1.110 + // The key fact that makes this work: if this.version == e.version,
1.111 + // then this thread has a right to observe (final) e.value.
1.112 + return e.value();
1.113 + // The fast path can fail for any of these reasons:
1.114 + // 1. no entry has been computed yet
1.115 + // 2. hash code collision (before or after reduction mod cache.length)
1.116 + // 3. an entry has been removed (either on this type or another)
1.117 + // 4. the GC has somehow managed to delete e.version and clear the reference
1.118 + return getFromBackup(cache, type);
1.119 + }
1.120 +
1.121 + /**
1.122 + * Removes the associated value for the given class.
1.123 + * If this value is subsequently {@linkplain #get read} for the same class,
1.124 + * its value will be reinitialized by invoking its {@link #computeValue computeValue} method.
1.125 + * This may result in an additional invocation of the
1.126 + * {@code computeValue} method for the given class.
1.127 + * <p>
1.128 + * In order to explain the interaction between {@code get} and {@code remove} calls,
1.129 + * we must model the state transitions of a class value to take into account
1.130 + * the alternation between uninitialized and initialized states.
1.131 + * To do this, number these states sequentially from zero, and note that
1.132 + * uninitialized (or removed) states are numbered with even numbers,
1.133 + * while initialized (or re-initialized) states have odd numbers.
1.134 + * <p>
1.135 + * When a thread {@code T} removes a class value in state {@code 2N},
1.136 + * nothing happens, since the class value is already uninitialized.
1.137 + * Otherwise, the state is advanced atomically to {@code 2N+1}.
1.138 + * <p>
1.139 + * When a thread {@code T} queries a class value in state {@code 2N},
1.140 + * the thread first attempts to initialize the class value to state {@code 2N+1}
1.141 + * by invoking {@code computeValue} and installing the resulting value.
1.142 + * <p>
1.143 + * When {@code T} attempts to install the newly computed value,
1.144 + * if the state is still at {@code 2N}, the class value will be initialized
1.145 + * with the computed value, advancing it to state {@code 2N+1}.
1.146 + * <p>
1.147 + * Otherwise, whether the new state is even or odd,
1.148 + * {@code T} will discard the newly computed value
1.149 + * and retry the {@code get} operation.
1.150 + * <p>
1.151 + * Discarding and retrying is an important proviso,
1.152 + * since otherwise {@code T} could potentially install
1.153 + * a disastrously stale value. For example:
1.154 + * <ul>
1.155 + * <li>{@code T} calls {@code CV.get(C)} and sees state {@code 2N}
1.156 + * <li>{@code T} quickly computes a time-dependent value {@code V0} and gets ready to install it
1.157 + * <li>{@code T} is hit by an unlucky paging or scheduling event, and goes to sleep for a long time
1.158 + * <li>...meanwhile, {@code T2} also calls {@code CV.get(C)} and sees state {@code 2N}
1.159 + * <li>{@code T2} quickly computes a similar time-dependent value {@code V1} and installs it on {@code CV.get(C)}
1.160 + * <li>{@code T2} (or a third thread) then calls {@code CV.remove(C)}, undoing {@code T2}'s work
1.161 + * <li> the previous actions of {@code T2} are repeated several times
1.162 + * <li> also, the relevant computed values change over time: {@code V1}, {@code V2}, ...
1.163 + * <li>...meanwhile, {@code T} wakes up and attempts to install {@code V0}; <em>this must fail</em>
1.164 + * </ul>
1.165 + * We can assume in the above scenario that {@code CV.computeValue} uses locks to properly
1.166 + * observe the time-dependent states as it computes {@code V1}, etc.
1.167 + * This does not remove the threat of a stale value, since there is a window of time
1.168 + * between the return of {@code computeValue} in {@code T} and the installation
1.169 + * of the the new value. No user synchronization is possible during this time.
1.170 + *
1.171 + * @param type the type whose class value must be removed
1.172 + * @throws NullPointerException if the argument is null
1.173 + */
1.174 + public void remove(Class<?> type) {
1.175 + ClassValueMap map = getMap(type);
1.176 + map.removeEntry(this);
1.177 + }
1.178 +
1.179 + // Possible functionality for JSR 292 MR 1
1.180 + /*public*/ void put(Class<?> type, T value) {
1.181 + ClassValueMap map = getMap(type);
1.182 + map.changeEntry(this, value);
1.183 + }
1.184 +
1.185 + /// --------
1.186 + /// Implementation...
1.187 + /// --------
1.188 +
1.189 + /** Return the cache, if it exists, else a dummy empty cache. */
1.190 + private static Entry<?>[] getCacheCarefully(Class<?> type) {
1.191 + // racing type.classValueMap{.cacheArray} : null => new Entry[X] <=> new Entry[Y]
1.192 + ClassValueMap map = type.classValueMap;
1.193 + if (map == null) return EMPTY_CACHE;
1.194 + Entry<?>[] cache = map.getCache();
1.195 + return cache;
1.196 + // invariant: returned value is safe to dereference and check for an Entry
1.197 + }
1.198 +
1.199 + /** Initial, one-element, empty cache used by all Class instances. Must never be filled. */
1.200 + private static final Entry<?>[] EMPTY_CACHE = { null };
1.201 +
1.202 + /**
1.203 + * Slow tail of ClassValue.get to retry at nearby locations in the cache,
1.204 + * or take a slow lock and check the hash table.
1.205 + * Called only if the first probe was empty or a collision.
1.206 + * This is a separate method, so compilers can process it independently.
1.207 + */
1.208 + private T getFromBackup(Entry<?>[] cache, Class<?> type) {
1.209 + Entry<T> e = probeBackupLocations(cache, this);
1.210 + if (e != null)
1.211 + return e.value();
1.212 + return getFromHashMap(type);
1.213 + }
1.214 +
1.215 + // Hack to suppress warnings on the (T) cast, which is a no-op.
1.216 + @SuppressWarnings("unchecked")
1.217 + Entry<T> castEntry(Entry<?> e) { return (Entry<T>) e; }
1.218 +
1.219 + /** Called when the fast path of get fails, and cache reprobe also fails.
1.220 + */
1.221 + private T getFromHashMap(Class<?> type) {
1.222 + // The fail-safe recovery is to fall back to the underlying classValueMap.
1.223 + ClassValueMap map = getMap(type);
1.224 + for (;;) {
1.225 + Entry<T> e = map.startEntry(this);
1.226 + if (!e.isPromise())
1.227 + return e.value();
1.228 + try {
1.229 + // Try to make a real entry for the promised version.
1.230 + e = makeEntry(e.version(), computeValue(type));
1.231 + } finally {
1.232 + // Whether computeValue throws or returns normally,
1.233 + // be sure to remove the empty entry.
1.234 + e = map.finishEntry(this, e);
1.235 + }
1.236 + if (e != null)
1.237 + return e.value();
1.238 + // else try again, in case a racing thread called remove (so e == null)
1.239 + }
1.240 + }
1.241 +
1.242 + /** Check that e is non-null, matches this ClassValue, and is live. */
1.243 + boolean match(Entry<?> e) {
1.244 + // racing e.version : null (blank) => unique Version token => null (GC-ed version)
1.245 + // non-racing this.version : v1 => v2 => ... (updates are read faithfully from volatile)
1.246 + return (e != null && e.get() == this.version);
1.247 + // invariant: No false positives on version match. Null is OK for false negative.
1.248 + // invariant: If version matches, then e.value is readable (final set in Entry.<init>)
1.249 + }
1.250 +
1.251 + /** Internal hash code for accessing Class.classValueMap.cacheArray. */
1.252 + final int hashCodeForCache = nextHashCode.getAndAdd(HASH_INCREMENT) & HASH_MASK;
1.253 +
1.254 + /** Value stream for hashCodeForCache. See similar structure in ThreadLocal. */
1.255 + private static final AtomicInteger nextHashCode = new AtomicInteger();
1.256 +
1.257 + /** Good for power-of-two tables. See similar structure in ThreadLocal. */
1.258 + private static final int HASH_INCREMENT = 0x61c88647;
1.259 +
1.260 + /** Mask a hash code to be positive but not too large, to prevent wraparound. */
1.261 + static final int HASH_MASK = (-1 >>> 2);
1.262 +
1.263 + /**
1.264 + * Private key for retrieval of this object from ClassValueMap.
1.265 + */
1.266 + static class Identity {
1.267 + }
1.268 + /**
1.269 + * This ClassValue's identity, expressed as an opaque object.
1.270 + * The main object {@code ClassValue.this} is incorrect since
1.271 + * subclasses may override {@code ClassValue.equals}, which
1.272 + * could confuse keys in the ClassValueMap.
1.273 + */
1.274 + final Identity identity = new Identity();
1.275 +
1.276 + /**
1.277 + * Current version for retrieving this class value from the cache.
1.278 + * Any number of computeValue calls can be cached in association with one version.
1.279 + * But the version changes when a remove (on any type) is executed.
1.280 + * A version change invalidates all cache entries for the affected ClassValue,
1.281 + * by marking them as stale. Stale cache entries do not force another call
1.282 + * to computeValue, but they do require a synchronized visit to a backing map.
1.283 + * <p>
1.284 + * All user-visible state changes on the ClassValue take place under
1.285 + * a lock inside the synchronized methods of ClassValueMap.
1.286 + * Readers (of ClassValue.get) are notified of such state changes
1.287 + * when this.version is bumped to a new token.
1.288 + * This variable must be volatile so that an unsynchronized reader
1.289 + * will receive the notification without delay.
1.290 + * <p>
1.291 + * If version were not volatile, one thread T1 could persistently hold onto
1.292 + * a stale value this.value == V1, while while another thread T2 advances
1.293 + * (under a lock) to this.value == V2. This will typically be harmless,
1.294 + * but if T1 and T2 interact causally via some other channel, such that
1.295 + * T1's further actions are constrained (in the JMM) to happen after
1.296 + * the V2 event, then T1's observation of V1 will be an error.
1.297 + * <p>
1.298 + * The practical effect of making this.version be volatile is that it cannot
1.299 + * be hoisted out of a loop (by an optimizing JIT) or otherwise cached.
1.300 + * Some machines may also require a barrier instruction to execute
1.301 + * before this.version.
1.302 + */
1.303 + private volatile Version<T> version = new Version<>(this);
1.304 + Version<T> version() { return version; }
1.305 + void bumpVersion() { version = new Version<>(this); }
1.306 + static class Version<T> {
1.307 + private final ClassValue<T> classValue;
1.308 + private final Entry<T> promise = new Entry<>(this);
1.309 + Version(ClassValue<T> classValue) { this.classValue = classValue; }
1.310 + ClassValue<T> classValue() { return classValue; }
1.311 + Entry<T> promise() { return promise; }
1.312 + boolean isLive() { return classValue.version() == this; }
1.313 + }
1.314 +
1.315 + /** One binding of a value to a class via a ClassValue.
1.316 + * States are:<ul>
1.317 + * <li> promise if value == Entry.this
1.318 + * <li> else dead if version == null
1.319 + * <li> else stale if version != classValue.version
1.320 + * <li> else live </ul>
1.321 + * Promises are never put into the cache; they only live in the
1.322 + * backing map while a computeValue call is in flight.
1.323 + * Once an entry goes stale, it can be reset at any time
1.324 + * into the dead state.
1.325 + */
1.326 + static class Entry<T> extends WeakReference<Version<T>> {
1.327 + final Object value; // usually of type T, but sometimes (Entry)this
1.328 + Entry(Version<T> version, T value) {
1.329 + super(version);
1.330 + this.value = value; // for a regular entry, value is of type T
1.331 + }
1.332 + private void assertNotPromise() { assert(!isPromise()); }
1.333 + /** For creating a promise. */
1.334 + Entry(Version<T> version) {
1.335 + super(version);
1.336 + this.value = this; // for a promise, value is not of type T, but Entry!
1.337 + }
1.338 + /** Fetch the value. This entry must not be a promise. */
1.339 + @SuppressWarnings("unchecked") // if !isPromise, type is T
1.340 + T value() { assertNotPromise(); return (T) value; }
1.341 + boolean isPromise() { return value == this; }
1.342 + Version<T> version() { return get(); }
1.343 + ClassValue<T> classValueOrNull() {
1.344 + Version<T> v = version();
1.345 + return (v == null) ? null : v.classValue();
1.346 + }
1.347 + boolean isLive() {
1.348 + Version<T> v = version();
1.349 + if (v == null) return false;
1.350 + if (v.isLive()) return true;
1.351 + clear();
1.352 + return false;
1.353 + }
1.354 + Entry<T> refreshVersion(Version<T> v2) {
1.355 + assertNotPromise();
1.356 + @SuppressWarnings("unchecked") // if !isPromise, type is T
1.357 + Entry<T> e2 = new Entry<>(v2, (T) value);
1.358 + clear();
1.359 + // value = null -- caller must drop
1.360 + return e2;
1.361 + }
1.362 + static final Entry<?> DEAD_ENTRY = new Entry<>(null, null);
1.363 + }
1.364 +
1.365 + /** Return the backing map associated with this type. */
1.366 + private static ClassValueMap getMap(Class<?> type) {
1.367 + // racing type.classValueMap : null (blank) => unique ClassValueMap
1.368 + // if a null is observed, a map is created (lazily, synchronously, uniquely)
1.369 + // all further access to that map is synchronized
1.370 + ClassValueMap map = type.classValueMap;
1.371 + if (map != null) return map;
1.372 + return initializeMap(type);
1.373 + }
1.374 +
1.375 + private static final Object CRITICAL_SECTION = new Object();
1.376 + private static ClassValueMap initializeMap(Class<?> type) {
1.377 + ClassValueMap map;
1.378 + synchronized (CRITICAL_SECTION) { // private object to avoid deadlocks
1.379 + // happens about once per type
1.380 + if ((map = type.classValueMap) == null)
1.381 + type.classValueMap = map = new ClassValueMap(type);
1.382 + }
1.383 + return map;
1.384 + }
1.385 +
1.386 + static <T> Entry<T> makeEntry(Version<T> explicitVersion, T value) {
1.387 + // Note that explicitVersion might be different from this.version.
1.388 + return new Entry<>(explicitVersion, value);
1.389 +
1.390 + // As soon as the Entry is put into the cache, the value will be
1.391 + // reachable via a data race (as defined by the Java Memory Model).
1.392 + // This race is benign, assuming the value object itself can be
1.393 + // read safely by multiple threads. This is up to the user.
1.394 + //
1.395 + // The entry and version fields themselves can be safely read via
1.396 + // a race because they are either final or have controlled states.
1.397 + // If the pointer from the entry to the version is still null,
1.398 + // or if the version goes immediately dead and is nulled out,
1.399 + // the reader will take the slow path and retry under a lock.
1.400 + }
1.401 +
1.402 + // The following class could also be top level and non-public:
1.403 +
1.404 + /** A backing map for all ClassValues, relative a single given type.
1.405 + * Gives a fully serialized "true state" for each pair (ClassValue cv, Class type).
1.406 + * Also manages an unserialized fast-path cache.
1.407 + */
1.408 + static class ClassValueMap extends WeakHashMap<ClassValue.Identity, Entry<?>> {
1.409 + private final Class<?> type;
1.410 + private Entry<?>[] cacheArray;
1.411 + private int cacheLoad, cacheLoadLimit;
1.412 +
1.413 + /** Number of entries initially allocated to each type when first used with any ClassValue.
1.414 + * It would be pointless to make this much smaller than the Class and ClassValueMap objects themselves.
1.415 + * Must be a power of 2.
1.416 + */
1.417 + private static final int INITIAL_ENTRIES = 32;
1.418 +
1.419 + /** Build a backing map for ClassValues, relative the given type.
1.420 + * Also, create an empty cache array and install it on the class.
1.421 + */
1.422 + ClassValueMap(Class<?> type) {
1.423 + this.type = type;
1.424 + sizeCache(INITIAL_ENTRIES);
1.425 + }
1.426 +
1.427 + Entry<?>[] getCache() { return cacheArray; }
1.428 +
1.429 + /** Initiate a query. Store a promise (placeholder) if there is no value yet. */
1.430 + synchronized
1.431 + <T> Entry<T> startEntry(ClassValue<T> classValue) {
1.432 + @SuppressWarnings("unchecked") // one map has entries for all value types <T>
1.433 + Entry<T> e = (Entry<T>) get(classValue.identity);
1.434 + Version<T> v = classValue.version();
1.435 + if (e == null) {
1.436 + e = v.promise();
1.437 + // The presence of a promise means that a value is pending for v.
1.438 + // Eventually, finishEntry will overwrite the promise.
1.439 + put(classValue.identity, e);
1.440 + // Note that the promise is never entered into the cache!
1.441 + return e;
1.442 + } else if (e.isPromise()) {
1.443 + // Somebody else has asked the same question.
1.444 + // Let the races begin!
1.445 + if (e.version() != v) {
1.446 + e = v.promise();
1.447 + put(classValue.identity, e);
1.448 + }
1.449 + return e;
1.450 + } else {
1.451 + // there is already a completed entry here; report it
1.452 + if (e.version() != v) {
1.453 + // There is a stale but valid entry here; make it fresh again.
1.454 + // Once an entry is in the hash table, we don't care what its version is.
1.455 + e = e.refreshVersion(v);
1.456 + put(classValue.identity, e);
1.457 + }
1.458 + // Add to the cache, to enable the fast path, next time.
1.459 + checkCacheLoad();
1.460 + addToCache(classValue, e);
1.461 + return e;
1.462 + }
1.463 + }
1.464 +
1.465 + /** Finish a query. Overwrite a matching placeholder. Drop stale incoming values. */
1.466 + synchronized
1.467 + <T> Entry<T> finishEntry(ClassValue<T> classValue, Entry<T> e) {
1.468 + @SuppressWarnings("unchecked") // one map has entries for all value types <T>
1.469 + Entry<T> e0 = (Entry<T>) get(classValue.identity);
1.470 + if (e == e0) {
1.471 + // We can get here during exception processing, unwinding from computeValue.
1.472 + assert(e.isPromise());
1.473 + remove(classValue.identity);
1.474 + return null;
1.475 + } else if (e0 != null && e0.isPromise() && e0.version() == e.version()) {
1.476 + // If e0 matches the intended entry, there has not been a remove call
1.477 + // between the previous startEntry and now. So now overwrite e0.
1.478 + Version<T> v = classValue.version();
1.479 + if (e.version() != v)
1.480 + e = e.refreshVersion(v);
1.481 + put(classValue.identity, e);
1.482 + // Add to the cache, to enable the fast path, next time.
1.483 + checkCacheLoad();
1.484 + addToCache(classValue, e);
1.485 + return e;
1.486 + } else {
1.487 + // Some sort of mismatch; caller must try again.
1.488 + return null;
1.489 + }
1.490 + }
1.491 +
1.492 + /** Remove an entry. */
1.493 + synchronized
1.494 + void removeEntry(ClassValue<?> classValue) {
1.495 + Entry<?> e = remove(classValue.identity);
1.496 + if (e == null) {
1.497 + // Uninitialized, and no pending calls to computeValue. No change.
1.498 + } else if (e.isPromise()) {
1.499 + // State is uninitialized, with a pending call to finishEntry.
1.500 + // Since remove is a no-op in such a state, keep the promise
1.501 + // by putting it back into the map.
1.502 + put(classValue.identity, e);
1.503 + } else {
1.504 + // In an initialized state. Bump forward, and de-initialize.
1.505 + classValue.bumpVersion();
1.506 + // Make all cache elements for this guy go stale.
1.507 + removeStaleEntries(classValue);
1.508 + }
1.509 + }
1.510 +
1.511 + /** Change the value for an entry. */
1.512 + synchronized
1.513 + <T> void changeEntry(ClassValue<T> classValue, T value) {
1.514 + @SuppressWarnings("unchecked") // one map has entries for all value types <T>
1.515 + Entry<T> e0 = (Entry<T>) get(classValue.identity);
1.516 + Version<T> version = classValue.version();
1.517 + if (e0 != null) {
1.518 + if (e0.version() == version && e0.value() == value)
1.519 + // no value change => no version change needed
1.520 + return;
1.521 + classValue.bumpVersion();
1.522 + removeStaleEntries(classValue);
1.523 + }
1.524 + Entry<T> e = makeEntry(version, value);
1.525 + put(classValue.identity, e);
1.526 + // Add to the cache, to enable the fast path, next time.
1.527 + checkCacheLoad();
1.528 + addToCache(classValue, e);
1.529 + }
1.530 +
1.531 + /// --------
1.532 + /// Cache management.
1.533 + /// --------
1.534 +
1.535 + // Statics do not need synchronization.
1.536 +
1.537 + /** Load the cache entry at the given (hashed) location. */
1.538 + static Entry<?> loadFromCache(Entry<?>[] cache, int i) {
1.539 + // non-racing cache.length : constant
1.540 + // racing cache[i & (mask)] : null <=> Entry
1.541 + return cache[i & (cache.length-1)];
1.542 + // invariant: returned value is null or well-constructed (ready to match)
1.543 + }
1.544 +
1.545 + /** Look in the cache, at the home location for the given ClassValue. */
1.546 + static <T> Entry<T> probeHomeLocation(Entry<?>[] cache, ClassValue<T> classValue) {
1.547 + return classValue.castEntry(loadFromCache(cache, classValue.hashCodeForCache));
1.548 + }
1.549 +
1.550 + /** Given that first probe was a collision, retry at nearby locations. */
1.551 + static <T> Entry<T> probeBackupLocations(Entry<?>[] cache, ClassValue<T> classValue) {
1.552 + if (PROBE_LIMIT <= 0) return null;
1.553 + // Probe the cache carefully, in a range of slots.
1.554 + int mask = (cache.length-1);
1.555 + int home = (classValue.hashCodeForCache & mask);
1.556 + Entry<?> e2 = cache[home]; // victim, if we find the real guy
1.557 + if (e2 == null) {
1.558 + return null; // if nobody is at home, no need to search nearby
1.559 + }
1.560 + // assume !classValue.match(e2), but do not assert, because of races
1.561 + int pos2 = -1;
1.562 + for (int i = home + 1; i < home + PROBE_LIMIT; i++) {
1.563 + Entry<?> e = cache[i & mask];
1.564 + if (e == null) {
1.565 + break; // only search within non-null runs
1.566 + }
1.567 + if (classValue.match(e)) {
1.568 + // relocate colliding entry e2 (from cache[home]) to first empty slot
1.569 + cache[home] = e;
1.570 + if (pos2 >= 0) {
1.571 + cache[i & mask] = Entry.DEAD_ENTRY;
1.572 + } else {
1.573 + pos2 = i;
1.574 + }
1.575 + cache[pos2 & mask] = ((entryDislocation(cache, pos2, e2) < PROBE_LIMIT)
1.576 + ? e2 // put e2 here if it fits
1.577 + : Entry.DEAD_ENTRY);
1.578 + return classValue.castEntry(e);
1.579 + }
1.580 + // Remember first empty slot, if any:
1.581 + if (!e.isLive() && pos2 < 0) pos2 = i;
1.582 + }
1.583 + return null;
1.584 + }
1.585 +
1.586 + /** How far out of place is e? */
1.587 + private static int entryDislocation(Entry<?>[] cache, int pos, Entry<?> e) {
1.588 + ClassValue<?> cv = e.classValueOrNull();
1.589 + if (cv == null) return 0; // entry is not live!
1.590 + int mask = (cache.length-1);
1.591 + return (pos - cv.hashCodeForCache) & mask;
1.592 + }
1.593 +
1.594 + /// --------
1.595 + /// Below this line all functions are private, and assume synchronized access.
1.596 + /// --------
1.597 +
1.598 + private void sizeCache(int length) {
1.599 + assert((length & (length-1)) == 0); // must be power of 2
1.600 + cacheLoad = 0;
1.601 + cacheLoadLimit = (int) ((double) length * CACHE_LOAD_LIMIT / 100);
1.602 + cacheArray = new Entry<?>[length];
1.603 + }
1.604 +
1.605 + /** Make sure the cache load stays below its limit, if possible. */
1.606 + private void checkCacheLoad() {
1.607 + if (cacheLoad >= cacheLoadLimit) {
1.608 + reduceCacheLoad();
1.609 + }
1.610 + }
1.611 + private void reduceCacheLoad() {
1.612 + removeStaleEntries();
1.613 + if (cacheLoad < cacheLoadLimit)
1.614 + return; // win
1.615 + Entry<?>[] oldCache = getCache();
1.616 + if (oldCache.length > HASH_MASK)
1.617 + return; // lose
1.618 + sizeCache(oldCache.length * 2);
1.619 + for (Entry<?> e : oldCache) {
1.620 + if (e != null && e.isLive()) {
1.621 + addToCache(e);
1.622 + }
1.623 + }
1.624 + }
1.625 +
1.626 + /** Remove stale entries in the given range.
1.627 + * Should be executed under a Map lock.
1.628 + */
1.629 + private void removeStaleEntries(Entry<?>[] cache, int begin, int count) {
1.630 + if (PROBE_LIMIT <= 0) return;
1.631 + int mask = (cache.length-1);
1.632 + int removed = 0;
1.633 + for (int i = begin; i < begin + count; i++) {
1.634 + Entry<?> e = cache[i & mask];
1.635 + if (e == null || e.isLive())
1.636 + continue; // skip null and live entries
1.637 + Entry<?> replacement = null;
1.638 + if (PROBE_LIMIT > 1) {
1.639 + // avoid breaking up a non-null run
1.640 + replacement = findReplacement(cache, i);
1.641 + }
1.642 + cache[i & mask] = replacement;
1.643 + if (replacement == null) removed += 1;
1.644 + }
1.645 + cacheLoad = Math.max(0, cacheLoad - removed);
1.646 + }
1.647 +
1.648 + /** Clearing a cache slot risks disconnecting following entries
1.649 + * from the head of a non-null run, which would allow them
1.650 + * to be found via reprobes. Find an entry after cache[begin]
1.651 + * to plug into the hole, or return null if none is needed.
1.652 + */
1.653 + private Entry<?> findReplacement(Entry<?>[] cache, int home1) {
1.654 + Entry<?> replacement = null;
1.655 + int haveReplacement = -1, replacementPos = 0;
1.656 + int mask = (cache.length-1);
1.657 + for (int i2 = home1 + 1; i2 < home1 + PROBE_LIMIT; i2++) {
1.658 + Entry<?> e2 = cache[i2 & mask];
1.659 + if (e2 == null) break; // End of non-null run.
1.660 + if (!e2.isLive()) continue; // Doomed anyway.
1.661 + int dis2 = entryDislocation(cache, i2, e2);
1.662 + if (dis2 == 0) continue; // e2 already optimally placed
1.663 + int home2 = i2 - dis2;
1.664 + if (home2 <= home1) {
1.665 + // e2 can replace entry at cache[home1]
1.666 + if (home2 == home1) {
1.667 + // Put e2 exactly where he belongs.
1.668 + haveReplacement = 1;
1.669 + replacementPos = i2;
1.670 + replacement = e2;
1.671 + } else if (haveReplacement <= 0) {
1.672 + haveReplacement = 0;
1.673 + replacementPos = i2;
1.674 + replacement = e2;
1.675 + }
1.676 + // And keep going, so we can favor larger dislocations.
1.677 + }
1.678 + }
1.679 + if (haveReplacement >= 0) {
1.680 + if (cache[(replacementPos+1) & mask] != null) {
1.681 + // Be conservative, to avoid breaking up a non-null run.
1.682 + cache[replacementPos & mask] = (Entry<?>) Entry.DEAD_ENTRY;
1.683 + } else {
1.684 + cache[replacementPos & mask] = null;
1.685 + cacheLoad -= 1;
1.686 + }
1.687 + }
1.688 + return replacement;
1.689 + }
1.690 +
1.691 + /** Remove stale entries in the range near classValue. */
1.692 + private void removeStaleEntries(ClassValue<?> classValue) {
1.693 + removeStaleEntries(getCache(), classValue.hashCodeForCache, PROBE_LIMIT);
1.694 + }
1.695 +
1.696 + /** Remove all stale entries, everywhere. */
1.697 + private void removeStaleEntries() {
1.698 + Entry<?>[] cache = getCache();
1.699 + removeStaleEntries(cache, 0, cache.length + PROBE_LIMIT - 1);
1.700 + }
1.701 +
1.702 + /** Add the given entry to the cache, in its home location, unless it is out of date. */
1.703 + private <T> void addToCache(Entry<T> e) {
1.704 + ClassValue<T> classValue = e.classValueOrNull();
1.705 + if (classValue != null)
1.706 + addToCache(classValue, e);
1.707 + }
1.708 +
1.709 + /** Add the given entry to the cache, in its home location. */
1.710 + private <T> void addToCache(ClassValue<T> classValue, Entry<T> e) {
1.711 + if (PROBE_LIMIT <= 0) return; // do not fill cache
1.712 + // Add e to the cache.
1.713 + Entry<?>[] cache = getCache();
1.714 + int mask = (cache.length-1);
1.715 + int home = classValue.hashCodeForCache & mask;
1.716 + Entry<?> e2 = placeInCache(cache, home, e, false);
1.717 + if (e2 == null) return; // done
1.718 + if (PROBE_LIMIT > 1) {
1.719 + // try to move e2 somewhere else in his probe range
1.720 + int dis2 = entryDislocation(cache, home, e2);
1.721 + int home2 = home - dis2;
1.722 + for (int i2 = home2; i2 < home2 + PROBE_LIMIT; i2++) {
1.723 + if (placeInCache(cache, i2 & mask, e2, true) == null) {
1.724 + return;
1.725 + }
1.726 + }
1.727 + }
1.728 + // Note: At this point, e2 is just dropped from the cache.
1.729 + }
1.730 +
1.731 + /** Store the given entry. Update cacheLoad, and return any live victim.
1.732 + * 'Gently' means return self rather than dislocating a live victim.
1.733 + */
1.734 + private Entry<?> placeInCache(Entry<?>[] cache, int pos, Entry<?> e, boolean gently) {
1.735 + Entry<?> e2 = overwrittenEntry(cache[pos]);
1.736 + if (gently && e2 != null) {
1.737 + // do not overwrite a live entry
1.738 + return e;
1.739 + } else {
1.740 + cache[pos] = e;
1.741 + return e2;
1.742 + }
1.743 + }
1.744 +
1.745 + /** Note an entry that is about to be overwritten.
1.746 + * If it is not live, quietly replace it by null.
1.747 + * If it is an actual null, increment cacheLoad,
1.748 + * because the caller is going to store something
1.749 + * in its place.
1.750 + */
1.751 + private <T> Entry<T> overwrittenEntry(Entry<T> e2) {
1.752 + if (e2 == null) cacheLoad += 1;
1.753 + else if (e2.isLive()) return e2;
1.754 + return null;
1.755 + }
1.756 +
1.757 + /** Percent loading of cache before resize. */
1.758 + private static final int CACHE_LOAD_LIMIT = 67; // 0..100
1.759 + /** Maximum number of probes to attempt. */
1.760 + private static final int PROBE_LIMIT = 6; // 1..
1.761 + // N.B. Set PROBE_LIMIT=0 to disable all fast paths.
1.762 + }
1.763 +}