rt/emul/compact/src/main/java/java/lang/ClassValue.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 10 Aug 2014 05:55:55 +0200
branchjdk8-b132
changeset 1649 98bdfed1a6e9
child 1653 bd151459ee4f
permissions -rw-r--r--
New exceptions as of JDK8-b132 needed for invoke dynamic
jaroslav@1649
     1
/*
jaroslav@1649
     2
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
jaroslav@1649
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1649
     4
 *
jaroslav@1649
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1649
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1649
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1649
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1649
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1649
    10
 *
jaroslav@1649
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1649
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1649
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1649
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1649
    15
 * accompanied this code).
jaroslav@1649
    16
 *
jaroslav@1649
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1649
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1649
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1649
    20
 *
jaroslav@1649
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1649
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1649
    23
 * questions.
jaroslav@1649
    24
 */
jaroslav@1649
    25
jaroslav@1649
    26
package java.lang;
jaroslav@1649
    27
jaroslav@1649
    28
import java.lang.ClassValue.ClassValueMap;
jaroslav@1649
    29
import java.util.WeakHashMap;
jaroslav@1649
    30
import java.lang.ref.WeakReference;
jaroslav@1649
    31
import java.util.concurrent.atomic.AtomicInteger;
jaroslav@1649
    32
jaroslav@1649
    33
import static java.lang.ClassValue.ClassValueMap.probeHomeLocation;
jaroslav@1649
    34
import static java.lang.ClassValue.ClassValueMap.probeBackupLocations;
jaroslav@1649
    35
jaroslav@1649
    36
/**
jaroslav@1649
    37
 * Lazily associate a computed value with (potentially) every type.
jaroslav@1649
    38
 * For example, if a dynamic language needs to construct a message dispatch
jaroslav@1649
    39
 * table for each class encountered at a message send call site,
jaroslav@1649
    40
 * it can use a {@code ClassValue} to cache information needed to
jaroslav@1649
    41
 * perform the message send quickly, for each class encountered.
jaroslav@1649
    42
 * @author John Rose, JSR 292 EG
jaroslav@1649
    43
 * @since 1.7
jaroslav@1649
    44
 */
jaroslav@1649
    45
public abstract class ClassValue<T> {
jaroslav@1649
    46
    /**
jaroslav@1649
    47
     * Sole constructor.  (For invocation by subclass constructors, typically
jaroslav@1649
    48
     * implicit.)
jaroslav@1649
    49
     */
jaroslav@1649
    50
    protected ClassValue() {
jaroslav@1649
    51
    }
jaroslav@1649
    52
jaroslav@1649
    53
    /**
jaroslav@1649
    54
     * Computes the given class's derived value for this {@code ClassValue}.
jaroslav@1649
    55
     * <p>
jaroslav@1649
    56
     * This method will be invoked within the first thread that accesses
jaroslav@1649
    57
     * the value with the {@link #get get} method.
jaroslav@1649
    58
     * <p>
jaroslav@1649
    59
     * Normally, this method is invoked at most once per class,
jaroslav@1649
    60
     * but it may be invoked again if there has been a call to
jaroslav@1649
    61
     * {@link #remove remove}.
jaroslav@1649
    62
     * <p>
jaroslav@1649
    63
     * If this method throws an exception, the corresponding call to {@code get}
jaroslav@1649
    64
     * will terminate abnormally with that exception, and no class value will be recorded.
jaroslav@1649
    65
     *
jaroslav@1649
    66
     * @param type the type whose class value must be computed
jaroslav@1649
    67
     * @return the newly computed value associated with this {@code ClassValue}, for the given class or interface
jaroslav@1649
    68
     * @see #get
jaroslav@1649
    69
     * @see #remove
jaroslav@1649
    70
     */
jaroslav@1649
    71
    protected abstract T computeValue(Class<?> type);
jaroslav@1649
    72
jaroslav@1649
    73
    /**
jaroslav@1649
    74
     * Returns the value for the given class.
jaroslav@1649
    75
     * If no value has yet been computed, it is obtained by
jaroslav@1649
    76
     * an invocation of the {@link #computeValue computeValue} method.
jaroslav@1649
    77
     * <p>
jaroslav@1649
    78
     * The actual installation of the value on the class
jaroslav@1649
    79
     * is performed atomically.
jaroslav@1649
    80
     * At that point, if several racing threads have
jaroslav@1649
    81
     * computed values, one is chosen, and returned to
jaroslav@1649
    82
     * all the racing threads.
jaroslav@1649
    83
     * <p>
jaroslav@1649
    84
     * The {@code type} parameter is typically a class, but it may be any type,
jaroslav@1649
    85
     * such as an interface, a primitive type (like {@code int.class}), or {@code void.class}.
jaroslav@1649
    86
     * <p>
jaroslav@1649
    87
     * In the absence of {@code remove} calls, a class value has a simple
jaroslav@1649
    88
     * state diagram:  uninitialized and initialized.
jaroslav@1649
    89
     * When {@code remove} calls are made,
jaroslav@1649
    90
     * the rules for value observation are more complex.
jaroslav@1649
    91
     * See the documentation for {@link #remove remove} for more information.
jaroslav@1649
    92
     *
jaroslav@1649
    93
     * @param type the type whose class value must be computed or retrieved
jaroslav@1649
    94
     * @return the current value associated with this {@code ClassValue}, for the given class or interface
jaroslav@1649
    95
     * @throws NullPointerException if the argument is null
jaroslav@1649
    96
     * @see #remove
jaroslav@1649
    97
     * @see #computeValue
jaroslav@1649
    98
     */
jaroslav@1649
    99
    public T get(Class<?> type) {
jaroslav@1649
   100
        // non-racing this.hashCodeForCache : final int
jaroslav@1649
   101
        Entry<?>[] cache;
jaroslav@1649
   102
        Entry<T> e = probeHomeLocation(cache = getCacheCarefully(type), this);
jaroslav@1649
   103
        // racing e : current value <=> stale value from current cache or from stale cache
jaroslav@1649
   104
        // invariant:  e is null or an Entry with readable Entry.version and Entry.value
jaroslav@1649
   105
        if (match(e))
jaroslav@1649
   106
            // invariant:  No false positive matches.  False negatives are OK if rare.
jaroslav@1649
   107
            // The key fact that makes this work: if this.version == e.version,
jaroslav@1649
   108
            // then this thread has a right to observe (final) e.value.
jaroslav@1649
   109
            return e.value();
jaroslav@1649
   110
        // The fast path can fail for any of these reasons:
jaroslav@1649
   111
        // 1. no entry has been computed yet
jaroslav@1649
   112
        // 2. hash code collision (before or after reduction mod cache.length)
jaroslav@1649
   113
        // 3. an entry has been removed (either on this type or another)
jaroslav@1649
   114
        // 4. the GC has somehow managed to delete e.version and clear the reference
jaroslav@1649
   115
        return getFromBackup(cache, type);
jaroslav@1649
   116
    }
jaroslav@1649
   117
jaroslav@1649
   118
    /**
jaroslav@1649
   119
     * Removes the associated value for the given class.
jaroslav@1649
   120
     * If this value is subsequently {@linkplain #get read} for the same class,
jaroslav@1649
   121
     * its value will be reinitialized by invoking its {@link #computeValue computeValue} method.
jaroslav@1649
   122
     * This may result in an additional invocation of the
jaroslav@1649
   123
     * {@code computeValue} method for the given class.
jaroslav@1649
   124
     * <p>
jaroslav@1649
   125
     * In order to explain the interaction between {@code get} and {@code remove} calls,
jaroslav@1649
   126
     * we must model the state transitions of a class value to take into account
jaroslav@1649
   127
     * the alternation between uninitialized and initialized states.
jaroslav@1649
   128
     * To do this, number these states sequentially from zero, and note that
jaroslav@1649
   129
     * uninitialized (or removed) states are numbered with even numbers,
jaroslav@1649
   130
     * while initialized (or re-initialized) states have odd numbers.
jaroslav@1649
   131
     * <p>
jaroslav@1649
   132
     * When a thread {@code T} removes a class value in state {@code 2N},
jaroslav@1649
   133
     * nothing happens, since the class value is already uninitialized.
jaroslav@1649
   134
     * Otherwise, the state is advanced atomically to {@code 2N+1}.
jaroslav@1649
   135
     * <p>
jaroslav@1649
   136
     * When a thread {@code T} queries a class value in state {@code 2N},
jaroslav@1649
   137
     * the thread first attempts to initialize the class value to state {@code 2N+1}
jaroslav@1649
   138
     * by invoking {@code computeValue} and installing the resulting value.
jaroslav@1649
   139
     * <p>
jaroslav@1649
   140
     * When {@code T} attempts to install the newly computed value,
jaroslav@1649
   141
     * if the state is still at {@code 2N}, the class value will be initialized
jaroslav@1649
   142
     * with the computed value, advancing it to state {@code 2N+1}.
jaroslav@1649
   143
     * <p>
jaroslav@1649
   144
     * Otherwise, whether the new state is even or odd,
jaroslav@1649
   145
     * {@code T} will discard the newly computed value
jaroslav@1649
   146
     * and retry the {@code get} operation.
jaroslav@1649
   147
     * <p>
jaroslav@1649
   148
     * Discarding and retrying is an important proviso,
jaroslav@1649
   149
     * since otherwise {@code T} could potentially install
jaroslav@1649
   150
     * a disastrously stale value.  For example:
jaroslav@1649
   151
     * <ul>
jaroslav@1649
   152
     * <li>{@code T} calls {@code CV.get(C)} and sees state {@code 2N}
jaroslav@1649
   153
     * <li>{@code T} quickly computes a time-dependent value {@code V0} and gets ready to install it
jaroslav@1649
   154
     * <li>{@code T} is hit by an unlucky paging or scheduling event, and goes to sleep for a long time
jaroslav@1649
   155
     * <li>...meanwhile, {@code T2} also calls {@code CV.get(C)} and sees state {@code 2N}
jaroslav@1649
   156
     * <li>{@code T2} quickly computes a similar time-dependent value {@code V1} and installs it on {@code CV.get(C)}
jaroslav@1649
   157
     * <li>{@code T2} (or a third thread) then calls {@code CV.remove(C)}, undoing {@code T2}'s work
jaroslav@1649
   158
     * <li> the previous actions of {@code T2} are repeated several times
jaroslav@1649
   159
     * <li> also, the relevant computed values change over time: {@code V1}, {@code V2}, ...
jaroslav@1649
   160
     * <li>...meanwhile, {@code T} wakes up and attempts to install {@code V0}; <em>this must fail</em>
jaroslav@1649
   161
     * </ul>
jaroslav@1649
   162
     * We can assume in the above scenario that {@code CV.computeValue} uses locks to properly
jaroslav@1649
   163
     * observe the time-dependent states as it computes {@code V1}, etc.
jaroslav@1649
   164
     * This does not remove the threat of a stale value, since there is a window of time
jaroslav@1649
   165
     * between the return of {@code computeValue} in {@code T} and the installation
jaroslav@1649
   166
     * of the the new value.  No user synchronization is possible during this time.
jaroslav@1649
   167
     *
jaroslav@1649
   168
     * @param type the type whose class value must be removed
jaroslav@1649
   169
     * @throws NullPointerException if the argument is null
jaroslav@1649
   170
     */
jaroslav@1649
   171
    public void remove(Class<?> type) {
jaroslav@1649
   172
        ClassValueMap map = getMap(type);
jaroslav@1649
   173
        map.removeEntry(this);
jaroslav@1649
   174
    }
jaroslav@1649
   175
jaroslav@1649
   176
    // Possible functionality for JSR 292 MR 1
jaroslav@1649
   177
    /*public*/ void put(Class<?> type, T value) {
jaroslav@1649
   178
        ClassValueMap map = getMap(type);
jaroslav@1649
   179
        map.changeEntry(this, value);
jaroslav@1649
   180
    }
jaroslav@1649
   181
jaroslav@1649
   182
    /// --------
jaroslav@1649
   183
    /// Implementation...
jaroslav@1649
   184
    /// --------
jaroslav@1649
   185
jaroslav@1649
   186
    /** Return the cache, if it exists, else a dummy empty cache. */
jaroslav@1649
   187
    private static Entry<?>[] getCacheCarefully(Class<?> type) {
jaroslav@1649
   188
        // racing type.classValueMap{.cacheArray} : null => new Entry[X] <=> new Entry[Y]
jaroslav@1649
   189
        ClassValueMap map = type.classValueMap;
jaroslav@1649
   190
        if (map == null)  return EMPTY_CACHE;
jaroslav@1649
   191
        Entry<?>[] cache = map.getCache();
jaroslav@1649
   192
        return cache;
jaroslav@1649
   193
        // invariant:  returned value is safe to dereference and check for an Entry
jaroslav@1649
   194
    }
jaroslav@1649
   195
jaroslav@1649
   196
    /** Initial, one-element, empty cache used by all Class instances.  Must never be filled. */
jaroslav@1649
   197
    private static final Entry<?>[] EMPTY_CACHE = { null };
jaroslav@1649
   198
jaroslav@1649
   199
    /**
jaroslav@1649
   200
     * Slow tail of ClassValue.get to retry at nearby locations in the cache,
jaroslav@1649
   201
     * or take a slow lock and check the hash table.
jaroslav@1649
   202
     * Called only if the first probe was empty or a collision.
jaroslav@1649
   203
     * This is a separate method, so compilers can process it independently.
jaroslav@1649
   204
     */
jaroslav@1649
   205
    private T getFromBackup(Entry<?>[] cache, Class<?> type) {
jaroslav@1649
   206
        Entry<T> e = probeBackupLocations(cache, this);
jaroslav@1649
   207
        if (e != null)
jaroslav@1649
   208
            return e.value();
jaroslav@1649
   209
        return getFromHashMap(type);
jaroslav@1649
   210
    }
jaroslav@1649
   211
jaroslav@1649
   212
    // Hack to suppress warnings on the (T) cast, which is a no-op.
jaroslav@1649
   213
    @SuppressWarnings("unchecked")
jaroslav@1649
   214
    Entry<T> castEntry(Entry<?> e) { return (Entry<T>) e; }
jaroslav@1649
   215
jaroslav@1649
   216
    /** Called when the fast path of get fails, and cache reprobe also fails.
jaroslav@1649
   217
     */
jaroslav@1649
   218
    private T getFromHashMap(Class<?> type) {
jaroslav@1649
   219
        // The fail-safe recovery is to fall back to the underlying classValueMap.
jaroslav@1649
   220
        ClassValueMap map = getMap(type);
jaroslav@1649
   221
        for (;;) {
jaroslav@1649
   222
            Entry<T> e = map.startEntry(this);
jaroslav@1649
   223
            if (!e.isPromise())
jaroslav@1649
   224
                return e.value();
jaroslav@1649
   225
            try {
jaroslav@1649
   226
                // Try to make a real entry for the promised version.
jaroslav@1649
   227
                e = makeEntry(e.version(), computeValue(type));
jaroslav@1649
   228
            } finally {
jaroslav@1649
   229
                // Whether computeValue throws or returns normally,
jaroslav@1649
   230
                // be sure to remove the empty entry.
jaroslav@1649
   231
                e = map.finishEntry(this, e);
jaroslav@1649
   232
            }
jaroslav@1649
   233
            if (e != null)
jaroslav@1649
   234
                return e.value();
jaroslav@1649
   235
            // else try again, in case a racing thread called remove (so e == null)
jaroslav@1649
   236
        }
jaroslav@1649
   237
    }
jaroslav@1649
   238
jaroslav@1649
   239
    /** Check that e is non-null, matches this ClassValue, and is live. */
jaroslav@1649
   240
    boolean match(Entry<?> e) {
jaroslav@1649
   241
        // racing e.version : null (blank) => unique Version token => null (GC-ed version)
jaroslav@1649
   242
        // non-racing this.version : v1 => v2 => ... (updates are read faithfully from volatile)
jaroslav@1649
   243
        return (e != null && e.get() == this.version);
jaroslav@1649
   244
        // invariant:  No false positives on version match.  Null is OK for false negative.
jaroslav@1649
   245
        // invariant:  If version matches, then e.value is readable (final set in Entry.<init>)
jaroslav@1649
   246
    }
jaroslav@1649
   247
jaroslav@1649
   248
    /** Internal hash code for accessing Class.classValueMap.cacheArray. */
jaroslav@1649
   249
    final int hashCodeForCache = nextHashCode.getAndAdd(HASH_INCREMENT) & HASH_MASK;
jaroslav@1649
   250
jaroslav@1649
   251
    /** Value stream for hashCodeForCache.  See similar structure in ThreadLocal. */
jaroslav@1649
   252
    private static final AtomicInteger nextHashCode = new AtomicInteger();
jaroslav@1649
   253
jaroslav@1649
   254
    /** Good for power-of-two tables.  See similar structure in ThreadLocal. */
jaroslav@1649
   255
    private static final int HASH_INCREMENT = 0x61c88647;
jaroslav@1649
   256
jaroslav@1649
   257
    /** Mask a hash code to be positive but not too large, to prevent wraparound. */
jaroslav@1649
   258
    static final int HASH_MASK = (-1 >>> 2);
jaroslav@1649
   259
jaroslav@1649
   260
    /**
jaroslav@1649
   261
     * Private key for retrieval of this object from ClassValueMap.
jaroslav@1649
   262
     */
jaroslav@1649
   263
    static class Identity {
jaroslav@1649
   264
    }
jaroslav@1649
   265
    /**
jaroslav@1649
   266
     * This ClassValue's identity, expressed as an opaque object.
jaroslav@1649
   267
     * The main object {@code ClassValue.this} is incorrect since
jaroslav@1649
   268
     * subclasses may override {@code ClassValue.equals}, which
jaroslav@1649
   269
     * could confuse keys in the ClassValueMap.
jaroslav@1649
   270
     */
jaroslav@1649
   271
    final Identity identity = new Identity();
jaroslav@1649
   272
jaroslav@1649
   273
    /**
jaroslav@1649
   274
     * Current version for retrieving this class value from the cache.
jaroslav@1649
   275
     * Any number of computeValue calls can be cached in association with one version.
jaroslav@1649
   276
     * But the version changes when a remove (on any type) is executed.
jaroslav@1649
   277
     * A version change invalidates all cache entries for the affected ClassValue,
jaroslav@1649
   278
     * by marking them as stale.  Stale cache entries do not force another call
jaroslav@1649
   279
     * to computeValue, but they do require a synchronized visit to a backing map.
jaroslav@1649
   280
     * <p>
jaroslav@1649
   281
     * All user-visible state changes on the ClassValue take place under
jaroslav@1649
   282
     * a lock inside the synchronized methods of ClassValueMap.
jaroslav@1649
   283
     * Readers (of ClassValue.get) are notified of such state changes
jaroslav@1649
   284
     * when this.version is bumped to a new token.
jaroslav@1649
   285
     * This variable must be volatile so that an unsynchronized reader
jaroslav@1649
   286
     * will receive the notification without delay.
jaroslav@1649
   287
     * <p>
jaroslav@1649
   288
     * If version were not volatile, one thread T1 could persistently hold onto
jaroslav@1649
   289
     * a stale value this.value == V1, while while another thread T2 advances
jaroslav@1649
   290
     * (under a lock) to this.value == V2.  This will typically be harmless,
jaroslav@1649
   291
     * but if T1 and T2 interact causally via some other channel, such that
jaroslav@1649
   292
     * T1's further actions are constrained (in the JMM) to happen after
jaroslav@1649
   293
     * the V2 event, then T1's observation of V1 will be an error.
jaroslav@1649
   294
     * <p>
jaroslav@1649
   295
     * The practical effect of making this.version be volatile is that it cannot
jaroslav@1649
   296
     * be hoisted out of a loop (by an optimizing JIT) or otherwise cached.
jaroslav@1649
   297
     * Some machines may also require a barrier instruction to execute
jaroslav@1649
   298
     * before this.version.
jaroslav@1649
   299
     */
jaroslav@1649
   300
    private volatile Version<T> version = new Version<>(this);
jaroslav@1649
   301
    Version<T> version() { return version; }
jaroslav@1649
   302
    void bumpVersion() { version = new Version<>(this); }
jaroslav@1649
   303
    static class Version<T> {
jaroslav@1649
   304
        private final ClassValue<T> classValue;
jaroslav@1649
   305
        private final Entry<T> promise = new Entry<>(this);
jaroslav@1649
   306
        Version(ClassValue<T> classValue) { this.classValue = classValue; }
jaroslav@1649
   307
        ClassValue<T> classValue() { return classValue; }
jaroslav@1649
   308
        Entry<T> promise() { return promise; }
jaroslav@1649
   309
        boolean isLive() { return classValue.version() == this; }
jaroslav@1649
   310
    }
jaroslav@1649
   311
jaroslav@1649
   312
    /** One binding of a value to a class via a ClassValue.
jaroslav@1649
   313
     *  States are:<ul>
jaroslav@1649
   314
     *  <li> promise if value == Entry.this
jaroslav@1649
   315
     *  <li> else dead if version == null
jaroslav@1649
   316
     *  <li> else stale if version != classValue.version
jaroslav@1649
   317
     *  <li> else live </ul>
jaroslav@1649
   318
     *  Promises are never put into the cache; they only live in the
jaroslav@1649
   319
     *  backing map while a computeValue call is in flight.
jaroslav@1649
   320
     *  Once an entry goes stale, it can be reset at any time
jaroslav@1649
   321
     *  into the dead state.
jaroslav@1649
   322
     */
jaroslav@1649
   323
    static class Entry<T> extends WeakReference<Version<T>> {
jaroslav@1649
   324
        final Object value;  // usually of type T, but sometimes (Entry)this
jaroslav@1649
   325
        Entry(Version<T> version, T value) {
jaroslav@1649
   326
            super(version);
jaroslav@1649
   327
            this.value = value;  // for a regular entry, value is of type T
jaroslav@1649
   328
        }
jaroslav@1649
   329
        private void assertNotPromise() { assert(!isPromise()); }
jaroslav@1649
   330
        /** For creating a promise. */
jaroslav@1649
   331
        Entry(Version<T> version) {
jaroslav@1649
   332
            super(version);
jaroslav@1649
   333
            this.value = this;  // for a promise, value is not of type T, but Entry!
jaroslav@1649
   334
        }
jaroslav@1649
   335
        /** Fetch the value.  This entry must not be a promise. */
jaroslav@1649
   336
        @SuppressWarnings("unchecked")  // if !isPromise, type is T
jaroslav@1649
   337
        T value() { assertNotPromise(); return (T) value; }
jaroslav@1649
   338
        boolean isPromise() { return value == this; }
jaroslav@1649
   339
        Version<T> version() { return get(); }
jaroslav@1649
   340
        ClassValue<T> classValueOrNull() {
jaroslav@1649
   341
            Version<T> v = version();
jaroslav@1649
   342
            return (v == null) ? null : v.classValue();
jaroslav@1649
   343
        }
jaroslav@1649
   344
        boolean isLive() {
jaroslav@1649
   345
            Version<T> v = version();
jaroslav@1649
   346
            if (v == null)  return false;
jaroslav@1649
   347
            if (v.isLive())  return true;
jaroslav@1649
   348
            clear();
jaroslav@1649
   349
            return false;
jaroslav@1649
   350
        }
jaroslav@1649
   351
        Entry<T> refreshVersion(Version<T> v2) {
jaroslav@1649
   352
            assertNotPromise();
jaroslav@1649
   353
            @SuppressWarnings("unchecked")  // if !isPromise, type is T
jaroslav@1649
   354
            Entry<T> e2 = new Entry<>(v2, (T) value);
jaroslav@1649
   355
            clear();
jaroslav@1649
   356
            // value = null -- caller must drop
jaroslav@1649
   357
            return e2;
jaroslav@1649
   358
        }
jaroslav@1649
   359
        static final Entry<?> DEAD_ENTRY = new Entry<>(null, null);
jaroslav@1649
   360
    }
jaroslav@1649
   361
jaroslav@1649
   362
    /** Return the backing map associated with this type. */
jaroslav@1649
   363
    private static ClassValueMap getMap(Class<?> type) {
jaroslav@1649
   364
        // racing type.classValueMap : null (blank) => unique ClassValueMap
jaroslav@1649
   365
        // if a null is observed, a map is created (lazily, synchronously, uniquely)
jaroslav@1649
   366
        // all further access to that map is synchronized
jaroslav@1649
   367
        ClassValueMap map = type.classValueMap;
jaroslav@1649
   368
        if (map != null)  return map;
jaroslav@1649
   369
        return initializeMap(type);
jaroslav@1649
   370
    }
jaroslav@1649
   371
jaroslav@1649
   372
    private static final Object CRITICAL_SECTION = new Object();
jaroslav@1649
   373
    private static ClassValueMap initializeMap(Class<?> type) {
jaroslav@1649
   374
        ClassValueMap map;
jaroslav@1649
   375
        synchronized (CRITICAL_SECTION) {  // private object to avoid deadlocks
jaroslav@1649
   376
            // happens about once per type
jaroslav@1649
   377
            if ((map = type.classValueMap) == null)
jaroslav@1649
   378
                type.classValueMap = map = new ClassValueMap(type);
jaroslav@1649
   379
        }
jaroslav@1649
   380
            return map;
jaroslav@1649
   381
        }
jaroslav@1649
   382
jaroslav@1649
   383
    static <T> Entry<T> makeEntry(Version<T> explicitVersion, T value) {
jaroslav@1649
   384
        // Note that explicitVersion might be different from this.version.
jaroslav@1649
   385
        return new Entry<>(explicitVersion, value);
jaroslav@1649
   386
jaroslav@1649
   387
        // As soon as the Entry is put into the cache, the value will be
jaroslav@1649
   388
        // reachable via a data race (as defined by the Java Memory Model).
jaroslav@1649
   389
        // This race is benign, assuming the value object itself can be
jaroslav@1649
   390
        // read safely by multiple threads.  This is up to the user.
jaroslav@1649
   391
        //
jaroslav@1649
   392
        // The entry and version fields themselves can be safely read via
jaroslav@1649
   393
        // a race because they are either final or have controlled states.
jaroslav@1649
   394
        // If the pointer from the entry to the version is still null,
jaroslav@1649
   395
        // or if the version goes immediately dead and is nulled out,
jaroslav@1649
   396
        // the reader will take the slow path and retry under a lock.
jaroslav@1649
   397
    }
jaroslav@1649
   398
jaroslav@1649
   399
    // The following class could also be top level and non-public:
jaroslav@1649
   400
jaroslav@1649
   401
    /** A backing map for all ClassValues, relative a single given type.
jaroslav@1649
   402
     *  Gives a fully serialized "true state" for each pair (ClassValue cv, Class type).
jaroslav@1649
   403
     *  Also manages an unserialized fast-path cache.
jaroslav@1649
   404
     */
jaroslav@1649
   405
    static class ClassValueMap extends WeakHashMap<ClassValue.Identity, Entry<?>> {
jaroslav@1649
   406
        private final Class<?> type;
jaroslav@1649
   407
        private Entry<?>[] cacheArray;
jaroslav@1649
   408
        private int cacheLoad, cacheLoadLimit;
jaroslav@1649
   409
jaroslav@1649
   410
        /** Number of entries initially allocated to each type when first used with any ClassValue.
jaroslav@1649
   411
         *  It would be pointless to make this much smaller than the Class and ClassValueMap objects themselves.
jaroslav@1649
   412
         *  Must be a power of 2.
jaroslav@1649
   413
         */
jaroslav@1649
   414
        private static final int INITIAL_ENTRIES = 32;
jaroslav@1649
   415
jaroslav@1649
   416
        /** Build a backing map for ClassValues, relative the given type.
jaroslav@1649
   417
         *  Also, create an empty cache array and install it on the class.
jaroslav@1649
   418
         */
jaroslav@1649
   419
        ClassValueMap(Class<?> type) {
jaroslav@1649
   420
            this.type = type;
jaroslav@1649
   421
            sizeCache(INITIAL_ENTRIES);
jaroslav@1649
   422
        }
jaroslav@1649
   423
jaroslav@1649
   424
        Entry<?>[] getCache() { return cacheArray; }
jaroslav@1649
   425
jaroslav@1649
   426
        /** Initiate a query.  Store a promise (placeholder) if there is no value yet. */
jaroslav@1649
   427
        synchronized
jaroslav@1649
   428
        <T> Entry<T> startEntry(ClassValue<T> classValue) {
jaroslav@1649
   429
            @SuppressWarnings("unchecked")  // one map has entries for all value types <T>
jaroslav@1649
   430
            Entry<T> e = (Entry<T>) get(classValue.identity);
jaroslav@1649
   431
            Version<T> v = classValue.version();
jaroslav@1649
   432
            if (e == null) {
jaroslav@1649
   433
                e = v.promise();
jaroslav@1649
   434
                // The presence of a promise means that a value is pending for v.
jaroslav@1649
   435
                // Eventually, finishEntry will overwrite the promise.
jaroslav@1649
   436
                put(classValue.identity, e);
jaroslav@1649
   437
                // Note that the promise is never entered into the cache!
jaroslav@1649
   438
                return e;
jaroslav@1649
   439
            } else if (e.isPromise()) {
jaroslav@1649
   440
                // Somebody else has asked the same question.
jaroslav@1649
   441
                // Let the races begin!
jaroslav@1649
   442
                if (e.version() != v) {
jaroslav@1649
   443
                    e = v.promise();
jaroslav@1649
   444
                    put(classValue.identity, e);
jaroslav@1649
   445
                }
jaroslav@1649
   446
                return e;
jaroslav@1649
   447
            } else {
jaroslav@1649
   448
                // there is already a completed entry here; report it
jaroslav@1649
   449
                if (e.version() != v) {
jaroslav@1649
   450
                    // There is a stale but valid entry here; make it fresh again.
jaroslav@1649
   451
                    // Once an entry is in the hash table, we don't care what its version is.
jaroslav@1649
   452
                    e = e.refreshVersion(v);
jaroslav@1649
   453
                    put(classValue.identity, e);
jaroslav@1649
   454
                }
jaroslav@1649
   455
                // Add to the cache, to enable the fast path, next time.
jaroslav@1649
   456
                checkCacheLoad();
jaroslav@1649
   457
                addToCache(classValue, e);
jaroslav@1649
   458
                return e;
jaroslav@1649
   459
            }
jaroslav@1649
   460
        }
jaroslav@1649
   461
jaroslav@1649
   462
        /** Finish a query.  Overwrite a matching placeholder.  Drop stale incoming values. */
jaroslav@1649
   463
        synchronized
jaroslav@1649
   464
        <T> Entry<T> finishEntry(ClassValue<T> classValue, Entry<T> e) {
jaroslav@1649
   465
            @SuppressWarnings("unchecked")  // one map has entries for all value types <T>
jaroslav@1649
   466
            Entry<T> e0 = (Entry<T>) get(classValue.identity);
jaroslav@1649
   467
            if (e == e0) {
jaroslav@1649
   468
                // We can get here during exception processing, unwinding from computeValue.
jaroslav@1649
   469
                assert(e.isPromise());
jaroslav@1649
   470
                remove(classValue.identity);
jaroslav@1649
   471
                return null;
jaroslav@1649
   472
            } else if (e0 != null && e0.isPromise() && e0.version() == e.version()) {
jaroslav@1649
   473
                // If e0 matches the intended entry, there has not been a remove call
jaroslav@1649
   474
                // between the previous startEntry and now.  So now overwrite e0.
jaroslav@1649
   475
                Version<T> v = classValue.version();
jaroslav@1649
   476
                if (e.version() != v)
jaroslav@1649
   477
                    e = e.refreshVersion(v);
jaroslav@1649
   478
                put(classValue.identity, e);
jaroslav@1649
   479
                // Add to the cache, to enable the fast path, next time.
jaroslav@1649
   480
                checkCacheLoad();
jaroslav@1649
   481
                addToCache(classValue, e);
jaroslav@1649
   482
                return e;
jaroslav@1649
   483
            } else {
jaroslav@1649
   484
                // Some sort of mismatch; caller must try again.
jaroslav@1649
   485
                return null;
jaroslav@1649
   486
            }
jaroslav@1649
   487
        }
jaroslav@1649
   488
jaroslav@1649
   489
        /** Remove an entry. */
jaroslav@1649
   490
        synchronized
jaroslav@1649
   491
        void removeEntry(ClassValue<?> classValue) {
jaroslav@1649
   492
            Entry<?> e = remove(classValue.identity);
jaroslav@1649
   493
            if (e == null) {
jaroslav@1649
   494
                // Uninitialized, and no pending calls to computeValue.  No change.
jaroslav@1649
   495
            } else if (e.isPromise()) {
jaroslav@1649
   496
                // State is uninitialized, with a pending call to finishEntry.
jaroslav@1649
   497
                // Since remove is a no-op in such a state, keep the promise
jaroslav@1649
   498
                // by putting it back into the map.
jaroslav@1649
   499
                put(classValue.identity, e);
jaroslav@1649
   500
            } else {
jaroslav@1649
   501
                // In an initialized state.  Bump forward, and de-initialize.
jaroslav@1649
   502
                classValue.bumpVersion();
jaroslav@1649
   503
                // Make all cache elements for this guy go stale.
jaroslav@1649
   504
                removeStaleEntries(classValue);
jaroslav@1649
   505
            }
jaroslav@1649
   506
        }
jaroslav@1649
   507
jaroslav@1649
   508
        /** Change the value for an entry. */
jaroslav@1649
   509
        synchronized
jaroslav@1649
   510
        <T> void changeEntry(ClassValue<T> classValue, T value) {
jaroslav@1649
   511
            @SuppressWarnings("unchecked")  // one map has entries for all value types <T>
jaroslav@1649
   512
            Entry<T> e0 = (Entry<T>) get(classValue.identity);
jaroslav@1649
   513
            Version<T> version = classValue.version();
jaroslav@1649
   514
            if (e0 != null) {
jaroslav@1649
   515
                if (e0.version() == version && e0.value() == value)
jaroslav@1649
   516
                    // no value change => no version change needed
jaroslav@1649
   517
                    return;
jaroslav@1649
   518
                classValue.bumpVersion();
jaroslav@1649
   519
                removeStaleEntries(classValue);
jaroslav@1649
   520
            }
jaroslav@1649
   521
            Entry<T> e = makeEntry(version, value);
jaroslav@1649
   522
            put(classValue.identity, e);
jaroslav@1649
   523
            // Add to the cache, to enable the fast path, next time.
jaroslav@1649
   524
            checkCacheLoad();
jaroslav@1649
   525
            addToCache(classValue, e);
jaroslav@1649
   526
        }
jaroslav@1649
   527
jaroslav@1649
   528
        /// --------
jaroslav@1649
   529
        /// Cache management.
jaroslav@1649
   530
        /// --------
jaroslav@1649
   531
jaroslav@1649
   532
        // Statics do not need synchronization.
jaroslav@1649
   533
jaroslav@1649
   534
        /** Load the cache entry at the given (hashed) location. */
jaroslav@1649
   535
        static Entry<?> loadFromCache(Entry<?>[] cache, int i) {
jaroslav@1649
   536
            // non-racing cache.length : constant
jaroslav@1649
   537
            // racing cache[i & (mask)] : null <=> Entry
jaroslav@1649
   538
            return cache[i & (cache.length-1)];
jaroslav@1649
   539
            // invariant:  returned value is null or well-constructed (ready to match)
jaroslav@1649
   540
        }
jaroslav@1649
   541
jaroslav@1649
   542
        /** Look in the cache, at the home location for the given ClassValue. */
jaroslav@1649
   543
        static <T> Entry<T> probeHomeLocation(Entry<?>[] cache, ClassValue<T> classValue) {
jaroslav@1649
   544
            return classValue.castEntry(loadFromCache(cache, classValue.hashCodeForCache));
jaroslav@1649
   545
        }
jaroslav@1649
   546
jaroslav@1649
   547
        /** Given that first probe was a collision, retry at nearby locations. */
jaroslav@1649
   548
        static <T> Entry<T> probeBackupLocations(Entry<?>[] cache, ClassValue<T> classValue) {
jaroslav@1649
   549
            if (PROBE_LIMIT <= 0)  return null;
jaroslav@1649
   550
            // Probe the cache carefully, in a range of slots.
jaroslav@1649
   551
            int mask = (cache.length-1);
jaroslav@1649
   552
            int home = (classValue.hashCodeForCache & mask);
jaroslav@1649
   553
            Entry<?> e2 = cache[home];  // victim, if we find the real guy
jaroslav@1649
   554
            if (e2 == null) {
jaroslav@1649
   555
                return null;   // if nobody is at home, no need to search nearby
jaroslav@1649
   556
            }
jaroslav@1649
   557
            // assume !classValue.match(e2), but do not assert, because of races
jaroslav@1649
   558
            int pos2 = -1;
jaroslav@1649
   559
            for (int i = home + 1; i < home + PROBE_LIMIT; i++) {
jaroslav@1649
   560
                Entry<?> e = cache[i & mask];
jaroslav@1649
   561
                if (e == null) {
jaroslav@1649
   562
                    break;   // only search within non-null runs
jaroslav@1649
   563
                }
jaroslav@1649
   564
                if (classValue.match(e)) {
jaroslav@1649
   565
                    // relocate colliding entry e2 (from cache[home]) to first empty slot
jaroslav@1649
   566
                    cache[home] = e;
jaroslav@1649
   567
                    if (pos2 >= 0) {
jaroslav@1649
   568
                        cache[i & mask] = Entry.DEAD_ENTRY;
jaroslav@1649
   569
                    } else {
jaroslav@1649
   570
                        pos2 = i;
jaroslav@1649
   571
                    }
jaroslav@1649
   572
                    cache[pos2 & mask] = ((entryDislocation(cache, pos2, e2) < PROBE_LIMIT)
jaroslav@1649
   573
                                          ? e2                  // put e2 here if it fits
jaroslav@1649
   574
                                          : Entry.DEAD_ENTRY);
jaroslav@1649
   575
                    return classValue.castEntry(e);
jaroslav@1649
   576
                }
jaroslav@1649
   577
                // Remember first empty slot, if any:
jaroslav@1649
   578
                if (!e.isLive() && pos2 < 0)  pos2 = i;
jaroslav@1649
   579
            }
jaroslav@1649
   580
            return null;
jaroslav@1649
   581
        }
jaroslav@1649
   582
jaroslav@1649
   583
        /** How far out of place is e? */
jaroslav@1649
   584
        private static int entryDislocation(Entry<?>[] cache, int pos, Entry<?> e) {
jaroslav@1649
   585
            ClassValue<?> cv = e.classValueOrNull();
jaroslav@1649
   586
            if (cv == null)  return 0;  // entry is not live!
jaroslav@1649
   587
            int mask = (cache.length-1);
jaroslav@1649
   588
            return (pos - cv.hashCodeForCache) & mask;
jaroslav@1649
   589
        }
jaroslav@1649
   590
jaroslav@1649
   591
        /// --------
jaroslav@1649
   592
        /// Below this line all functions are private, and assume synchronized access.
jaroslav@1649
   593
        /// --------
jaroslav@1649
   594
jaroslav@1649
   595
        private void sizeCache(int length) {
jaroslav@1649
   596
            assert((length & (length-1)) == 0);  // must be power of 2
jaroslav@1649
   597
            cacheLoad = 0;
jaroslav@1649
   598
            cacheLoadLimit = (int) ((double) length * CACHE_LOAD_LIMIT / 100);
jaroslav@1649
   599
            cacheArray = new Entry<?>[length];
jaroslav@1649
   600
        }
jaroslav@1649
   601
jaroslav@1649
   602
        /** Make sure the cache load stays below its limit, if possible. */
jaroslav@1649
   603
        private void checkCacheLoad() {
jaroslav@1649
   604
            if (cacheLoad >= cacheLoadLimit) {
jaroslav@1649
   605
                reduceCacheLoad();
jaroslav@1649
   606
            }
jaroslav@1649
   607
        }
jaroslav@1649
   608
        private void reduceCacheLoad() {
jaroslav@1649
   609
            removeStaleEntries();
jaroslav@1649
   610
            if (cacheLoad < cacheLoadLimit)
jaroslav@1649
   611
                return;  // win
jaroslav@1649
   612
            Entry<?>[] oldCache = getCache();
jaroslav@1649
   613
            if (oldCache.length > HASH_MASK)
jaroslav@1649
   614
                return;  // lose
jaroslav@1649
   615
            sizeCache(oldCache.length * 2);
jaroslav@1649
   616
            for (Entry<?> e : oldCache) {
jaroslav@1649
   617
                if (e != null && e.isLive()) {
jaroslav@1649
   618
                    addToCache(e);
jaroslav@1649
   619
                }
jaroslav@1649
   620
            }
jaroslav@1649
   621
        }
jaroslav@1649
   622
jaroslav@1649
   623
        /** Remove stale entries in the given range.
jaroslav@1649
   624
         *  Should be executed under a Map lock.
jaroslav@1649
   625
         */
jaroslav@1649
   626
        private void removeStaleEntries(Entry<?>[] cache, int begin, int count) {
jaroslav@1649
   627
            if (PROBE_LIMIT <= 0)  return;
jaroslav@1649
   628
            int mask = (cache.length-1);
jaroslav@1649
   629
            int removed = 0;
jaroslav@1649
   630
            for (int i = begin; i < begin + count; i++) {
jaroslav@1649
   631
                Entry<?> e = cache[i & mask];
jaroslav@1649
   632
                if (e == null || e.isLive())
jaroslav@1649
   633
                    continue;  // skip null and live entries
jaroslav@1649
   634
                Entry<?> replacement = null;
jaroslav@1649
   635
                if (PROBE_LIMIT > 1) {
jaroslav@1649
   636
                    // avoid breaking up a non-null run
jaroslav@1649
   637
                    replacement = findReplacement(cache, i);
jaroslav@1649
   638
                }
jaroslav@1649
   639
                cache[i & mask] = replacement;
jaroslav@1649
   640
                if (replacement == null)  removed += 1;
jaroslav@1649
   641
            }
jaroslav@1649
   642
            cacheLoad = Math.max(0, cacheLoad - removed);
jaroslav@1649
   643
        }
jaroslav@1649
   644
jaroslav@1649
   645
        /** Clearing a cache slot risks disconnecting following entries
jaroslav@1649
   646
         *  from the head of a non-null run, which would allow them
jaroslav@1649
   647
         *  to be found via reprobes.  Find an entry after cache[begin]
jaroslav@1649
   648
         *  to plug into the hole, or return null if none is needed.
jaroslav@1649
   649
         */
jaroslav@1649
   650
        private Entry<?> findReplacement(Entry<?>[] cache, int home1) {
jaroslav@1649
   651
            Entry<?> replacement = null;
jaroslav@1649
   652
            int haveReplacement = -1, replacementPos = 0;
jaroslav@1649
   653
            int mask = (cache.length-1);
jaroslav@1649
   654
            for (int i2 = home1 + 1; i2 < home1 + PROBE_LIMIT; i2++) {
jaroslav@1649
   655
                Entry<?> e2 = cache[i2 & mask];
jaroslav@1649
   656
                if (e2 == null)  break;  // End of non-null run.
jaroslav@1649
   657
                if (!e2.isLive())  continue;  // Doomed anyway.
jaroslav@1649
   658
                int dis2 = entryDislocation(cache, i2, e2);
jaroslav@1649
   659
                if (dis2 == 0)  continue;  // e2 already optimally placed
jaroslav@1649
   660
                int home2 = i2 - dis2;
jaroslav@1649
   661
                if (home2 <= home1) {
jaroslav@1649
   662
                    // e2 can replace entry at cache[home1]
jaroslav@1649
   663
                    if (home2 == home1) {
jaroslav@1649
   664
                        // Put e2 exactly where he belongs.
jaroslav@1649
   665
                        haveReplacement = 1;
jaroslav@1649
   666
                        replacementPos = i2;
jaroslav@1649
   667
                        replacement = e2;
jaroslav@1649
   668
                    } else if (haveReplacement <= 0) {
jaroslav@1649
   669
                        haveReplacement = 0;
jaroslav@1649
   670
                        replacementPos = i2;
jaroslav@1649
   671
                        replacement = e2;
jaroslav@1649
   672
                    }
jaroslav@1649
   673
                    // And keep going, so we can favor larger dislocations.
jaroslav@1649
   674
                }
jaroslav@1649
   675
            }
jaroslav@1649
   676
            if (haveReplacement >= 0) {
jaroslav@1649
   677
                if (cache[(replacementPos+1) & mask] != null) {
jaroslav@1649
   678
                    // Be conservative, to avoid breaking up a non-null run.
jaroslav@1649
   679
                    cache[replacementPos & mask] = (Entry<?>) Entry.DEAD_ENTRY;
jaroslav@1649
   680
                } else {
jaroslav@1649
   681
                    cache[replacementPos & mask] = null;
jaroslav@1649
   682
                    cacheLoad -= 1;
jaroslav@1649
   683
                }
jaroslav@1649
   684
            }
jaroslav@1649
   685
            return replacement;
jaroslav@1649
   686
        }
jaroslav@1649
   687
jaroslav@1649
   688
        /** Remove stale entries in the range near classValue. */
jaroslav@1649
   689
        private void removeStaleEntries(ClassValue<?> classValue) {
jaroslav@1649
   690
            removeStaleEntries(getCache(), classValue.hashCodeForCache, PROBE_LIMIT);
jaroslav@1649
   691
        }
jaroslav@1649
   692
jaroslav@1649
   693
        /** Remove all stale entries, everywhere. */
jaroslav@1649
   694
        private void removeStaleEntries() {
jaroslav@1649
   695
            Entry<?>[] cache = getCache();
jaroslav@1649
   696
            removeStaleEntries(cache, 0, cache.length + PROBE_LIMIT - 1);
jaroslav@1649
   697
        }
jaroslav@1649
   698
jaroslav@1649
   699
        /** Add the given entry to the cache, in its home location, unless it is out of date. */
jaroslav@1649
   700
        private <T> void addToCache(Entry<T> e) {
jaroslav@1649
   701
            ClassValue<T> classValue = e.classValueOrNull();
jaroslav@1649
   702
            if (classValue != null)
jaroslav@1649
   703
                addToCache(classValue, e);
jaroslav@1649
   704
        }
jaroslav@1649
   705
jaroslav@1649
   706
        /** Add the given entry to the cache, in its home location. */
jaroslav@1649
   707
        private <T> void addToCache(ClassValue<T> classValue, Entry<T> e) {
jaroslav@1649
   708
            if (PROBE_LIMIT <= 0)  return;  // do not fill cache
jaroslav@1649
   709
            // Add e to the cache.
jaroslav@1649
   710
            Entry<?>[] cache = getCache();
jaroslav@1649
   711
            int mask = (cache.length-1);
jaroslav@1649
   712
            int home = classValue.hashCodeForCache & mask;
jaroslav@1649
   713
            Entry<?> e2 = placeInCache(cache, home, e, false);
jaroslav@1649
   714
            if (e2 == null)  return;  // done
jaroslav@1649
   715
            if (PROBE_LIMIT > 1) {
jaroslav@1649
   716
                // try to move e2 somewhere else in his probe range
jaroslav@1649
   717
                int dis2 = entryDislocation(cache, home, e2);
jaroslav@1649
   718
                int home2 = home - dis2;
jaroslav@1649
   719
                for (int i2 = home2; i2 < home2 + PROBE_LIMIT; i2++) {
jaroslav@1649
   720
                    if (placeInCache(cache, i2 & mask, e2, true) == null) {
jaroslav@1649
   721
                        return;
jaroslav@1649
   722
                    }
jaroslav@1649
   723
                }
jaroslav@1649
   724
            }
jaroslav@1649
   725
            // Note:  At this point, e2 is just dropped from the cache.
jaroslav@1649
   726
        }
jaroslav@1649
   727
jaroslav@1649
   728
        /** Store the given entry.  Update cacheLoad, and return any live victim.
jaroslav@1649
   729
         *  'Gently' means return self rather than dislocating a live victim.
jaroslav@1649
   730
         */
jaroslav@1649
   731
        private Entry<?> placeInCache(Entry<?>[] cache, int pos, Entry<?> e, boolean gently) {
jaroslav@1649
   732
            Entry<?> e2 = overwrittenEntry(cache[pos]);
jaroslav@1649
   733
            if (gently && e2 != null) {
jaroslav@1649
   734
                // do not overwrite a live entry
jaroslav@1649
   735
                return e;
jaroslav@1649
   736
            } else {
jaroslav@1649
   737
                cache[pos] = e;
jaroslav@1649
   738
                return e2;
jaroslav@1649
   739
            }
jaroslav@1649
   740
        }
jaroslav@1649
   741
jaroslav@1649
   742
        /** Note an entry that is about to be overwritten.
jaroslav@1649
   743
         *  If it is not live, quietly replace it by null.
jaroslav@1649
   744
         *  If it is an actual null, increment cacheLoad,
jaroslav@1649
   745
         *  because the caller is going to store something
jaroslav@1649
   746
         *  in its place.
jaroslav@1649
   747
         */
jaroslav@1649
   748
        private <T> Entry<T> overwrittenEntry(Entry<T> e2) {
jaroslav@1649
   749
            if (e2 == null)  cacheLoad += 1;
jaroslav@1649
   750
            else if (e2.isLive())  return e2;
jaroslav@1649
   751
            return null;
jaroslav@1649
   752
        }
jaroslav@1649
   753
jaroslav@1649
   754
        /** Percent loading of cache before resize. */
jaroslav@1649
   755
        private static final int CACHE_LOAD_LIMIT = 67;  // 0..100
jaroslav@1649
   756
        /** Maximum number of probes to attempt. */
jaroslav@1649
   757
        private static final int PROBE_LIMIT      =  6;       // 1..
jaroslav@1649
   758
        // N.B.  Set PROBE_LIMIT=0 to disable all fast paths.
jaroslav@1649
   759
    }
jaroslav@1649
   760
}