emul/compact/src/main/java/java/lang/ThreadLocal.java
author Jaroslav Tulach <jtulach@netbeans.org>
Thu, 12 Sep 2013 12:19:53 +0200
branchjdk7-b147
changeset 1280 c1e76ee31360
permissions -rw-r--r--
Need access to thread local class
jtulach@1280
     1
/*
jtulach@1280
     2
 * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
jtulach@1280
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jtulach@1280
     4
 *
jtulach@1280
     5
 * This code is free software; you can redistribute it and/or modify it
jtulach@1280
     6
 * under the terms of the GNU General Public License version 2 only, as
jtulach@1280
     7
 * published by the Free Software Foundation.  Oracle designates this
jtulach@1280
     8
 * particular file as subject to the "Classpath" exception as provided
jtulach@1280
     9
 * by Oracle in the LICENSE file that accompanied this code.
jtulach@1280
    10
 *
jtulach@1280
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jtulach@1280
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jtulach@1280
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jtulach@1280
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jtulach@1280
    15
 * accompanied this code).
jtulach@1280
    16
 *
jtulach@1280
    17
 * You should have received a copy of the GNU General Public License version
jtulach@1280
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jtulach@1280
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jtulach@1280
    20
 *
jtulach@1280
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jtulach@1280
    22
 * or visit www.oracle.com if you need additional information or have any
jtulach@1280
    23
 * questions.
jtulach@1280
    24
 */
jtulach@1280
    25
jtulach@1280
    26
package java.lang;
jtulach@1280
    27
import java.lang.ref.*;
jtulach@1280
    28
import java.util.concurrent.atomic.AtomicInteger;
jtulach@1280
    29
jtulach@1280
    30
/**
jtulach@1280
    31
 * This class provides thread-local variables.  These variables differ from
jtulach@1280
    32
 * their normal counterparts in that each thread that accesses one (via its
jtulach@1280
    33
 * <tt>get</tt> or <tt>set</tt> method) has its own, independently initialized
jtulach@1280
    34
 * copy of the variable.  <tt>ThreadLocal</tt> instances are typically private
jtulach@1280
    35
 * static fields in classes that wish to associate state with a thread (e.g.,
jtulach@1280
    36
 * a user ID or Transaction ID).
jtulach@1280
    37
 *
jtulach@1280
    38
 * <p>For example, the class below generates unique identifiers local to each
jtulach@1280
    39
 * thread.
jtulach@1280
    40
 * A thread's id is assigned the first time it invokes <tt>ThreadId.get()</tt>
jtulach@1280
    41
 * and remains unchanged on subsequent calls.
jtulach@1280
    42
 * <pre>
jtulach@1280
    43
 * import java.util.concurrent.atomic.AtomicInteger;
jtulach@1280
    44
 *
jtulach@1280
    45
 * public class ThreadId {
jtulach@1280
    46
 *     // Atomic integer containing the next thread ID to be assigned
jtulach@1280
    47
 *     private static final AtomicInteger nextId = new AtomicInteger(0);
jtulach@1280
    48
 *
jtulach@1280
    49
 *     // Thread local variable containing each thread's ID
jtulach@1280
    50
 *     private static final ThreadLocal&lt;Integer> threadId =
jtulach@1280
    51
 *         new ThreadLocal&lt;Integer>() {
jtulach@1280
    52
 *             &#64;Override protected Integer initialValue() {
jtulach@1280
    53
 *                 return nextId.getAndIncrement();
jtulach@1280
    54
 *         }
jtulach@1280
    55
 *     };
jtulach@1280
    56
 *
jtulach@1280
    57
 *     // Returns the current thread's unique ID, assigning it if necessary
jtulach@1280
    58
 *     public static int get() {
jtulach@1280
    59
 *         return threadId.get();
jtulach@1280
    60
 *     }
jtulach@1280
    61
 * }
jtulach@1280
    62
 * </pre>
jtulach@1280
    63
 * <p>Each thread holds an implicit reference to its copy of a thread-local
jtulach@1280
    64
 * variable as long as the thread is alive and the <tt>ThreadLocal</tt>
jtulach@1280
    65
 * instance is accessible; after a thread goes away, all of its copies of
jtulach@1280
    66
 * thread-local instances are subject to garbage collection (unless other
jtulach@1280
    67
 * references to these copies exist).
jtulach@1280
    68
 *
jtulach@1280
    69
 * @author  Josh Bloch and Doug Lea
jtulach@1280
    70
 * @since   1.2
jtulach@1280
    71
 */
jtulach@1280
    72
public class ThreadLocal<T> {
jtulach@1280
    73
    /**
jtulach@1280
    74
     * ThreadLocals rely on per-thread linear-probe hash maps attached
jtulach@1280
    75
     * to each thread (Thread.threadLocals and
jtulach@1280
    76
     * inheritableThreadLocals).  The ThreadLocal objects act as keys,
jtulach@1280
    77
     * searched via threadLocalHashCode.  This is a custom hash code
jtulach@1280
    78
     * (useful only within ThreadLocalMaps) that eliminates collisions
jtulach@1280
    79
     * in the common case where consecutively constructed ThreadLocals
jtulach@1280
    80
     * are used by the same threads, while remaining well-behaved in
jtulach@1280
    81
     * less common cases.
jtulach@1280
    82
     */
jtulach@1280
    83
    private final int threadLocalHashCode = nextHashCode();
jtulach@1280
    84
jtulach@1280
    85
    /**
jtulach@1280
    86
     * The next hash code to be given out. Updated atomically. Starts at
jtulach@1280
    87
     * zero.
jtulach@1280
    88
     */
jtulach@1280
    89
    private static AtomicInteger nextHashCode =
jtulach@1280
    90
        new AtomicInteger();
jtulach@1280
    91
jtulach@1280
    92
    /**
jtulach@1280
    93
     * The difference between successively generated hash codes - turns
jtulach@1280
    94
     * implicit sequential thread-local IDs into near-optimally spread
jtulach@1280
    95
     * multiplicative hash values for power-of-two-sized tables.
jtulach@1280
    96
     */
jtulach@1280
    97
    private static final int HASH_INCREMENT = 0x61c88647;
jtulach@1280
    98
jtulach@1280
    99
    /**
jtulach@1280
   100
     * Returns the next hash code.
jtulach@1280
   101
     */
jtulach@1280
   102
    private static int nextHashCode() {
jtulach@1280
   103
        return nextHashCode.getAndAdd(HASH_INCREMENT);
jtulach@1280
   104
    }
jtulach@1280
   105
jtulach@1280
   106
    /**
jtulach@1280
   107
     * Returns the current thread's "initial value" for this
jtulach@1280
   108
     * thread-local variable.  This method will be invoked the first
jtulach@1280
   109
     * time a thread accesses the variable with the {@link #get}
jtulach@1280
   110
     * method, unless the thread previously invoked the {@link #set}
jtulach@1280
   111
     * method, in which case the <tt>initialValue</tt> method will not
jtulach@1280
   112
     * be invoked for the thread.  Normally, this method is invoked at
jtulach@1280
   113
     * most once per thread, but it may be invoked again in case of
jtulach@1280
   114
     * subsequent invocations of {@link #remove} followed by {@link #get}.
jtulach@1280
   115
     *
jtulach@1280
   116
     * <p>This implementation simply returns <tt>null</tt>; if the
jtulach@1280
   117
     * programmer desires thread-local variables to have an initial
jtulach@1280
   118
     * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be
jtulach@1280
   119
     * subclassed, and this method overridden.  Typically, an
jtulach@1280
   120
     * anonymous inner class will be used.
jtulach@1280
   121
     *
jtulach@1280
   122
     * @return the initial value for this thread-local
jtulach@1280
   123
     */
jtulach@1280
   124
    protected T initialValue() {
jtulach@1280
   125
        return null;
jtulach@1280
   126
    }
jtulach@1280
   127
jtulach@1280
   128
    /**
jtulach@1280
   129
     * Creates a thread local variable.
jtulach@1280
   130
     */
jtulach@1280
   131
    public ThreadLocal() {
jtulach@1280
   132
    }
jtulach@1280
   133
jtulach@1280
   134
    /**
jtulach@1280
   135
     * Returns the value in the current thread's copy of this
jtulach@1280
   136
     * thread-local variable.  If the variable has no value for the
jtulach@1280
   137
     * current thread, it is first initialized to the value returned
jtulach@1280
   138
     * by an invocation of the {@link #initialValue} method.
jtulach@1280
   139
     *
jtulach@1280
   140
     * @return the current thread's value of this thread-local
jtulach@1280
   141
     */
jtulach@1280
   142
    public T get() {
jtulach@1280
   143
        Thread t = Thread.currentThread();
jtulach@1280
   144
        ThreadLocalMap map = getMap(t);
jtulach@1280
   145
        if (map != null) {
jtulach@1280
   146
            ThreadLocalMap.Entry e = map.getEntry(this);
jtulach@1280
   147
            if (e != null)
jtulach@1280
   148
                return (T)e.value;
jtulach@1280
   149
        }
jtulach@1280
   150
        return setInitialValue();
jtulach@1280
   151
    }
jtulach@1280
   152
jtulach@1280
   153
    /**
jtulach@1280
   154
     * Variant of set() to establish initialValue. Used instead
jtulach@1280
   155
     * of set() in case user has overridden the set() method.
jtulach@1280
   156
     *
jtulach@1280
   157
     * @return the initial value
jtulach@1280
   158
     */
jtulach@1280
   159
    private T setInitialValue() {
jtulach@1280
   160
        T value = initialValue();
jtulach@1280
   161
        Thread t = Thread.currentThread();
jtulach@1280
   162
        ThreadLocalMap map = getMap(t);
jtulach@1280
   163
        if (map != null)
jtulach@1280
   164
            map.set(this, value);
jtulach@1280
   165
        else
jtulach@1280
   166
            createMap(t, value);
jtulach@1280
   167
        return value;
jtulach@1280
   168
    }
jtulach@1280
   169
jtulach@1280
   170
    /**
jtulach@1280
   171
     * Sets the current thread's copy of this thread-local variable
jtulach@1280
   172
     * to the specified value.  Most subclasses will have no need to
jtulach@1280
   173
     * override this method, relying solely on the {@link #initialValue}
jtulach@1280
   174
     * method to set the values of thread-locals.
jtulach@1280
   175
     *
jtulach@1280
   176
     * @param value the value to be stored in the current thread's copy of
jtulach@1280
   177
     *        this thread-local.
jtulach@1280
   178
     */
jtulach@1280
   179
    public void set(T value) {
jtulach@1280
   180
        Thread t = Thread.currentThread();
jtulach@1280
   181
        ThreadLocalMap map = getMap(t);
jtulach@1280
   182
        if (map != null)
jtulach@1280
   183
            map.set(this, value);
jtulach@1280
   184
        else
jtulach@1280
   185
            createMap(t, value);
jtulach@1280
   186
    }
jtulach@1280
   187
jtulach@1280
   188
    /**
jtulach@1280
   189
     * Removes the current thread's value for this thread-local
jtulach@1280
   190
     * variable.  If this thread-local variable is subsequently
jtulach@1280
   191
     * {@linkplain #get read} by the current thread, its value will be
jtulach@1280
   192
     * reinitialized by invoking its {@link #initialValue} method,
jtulach@1280
   193
     * unless its value is {@linkplain #set set} by the current thread
jtulach@1280
   194
     * in the interim.  This may result in multiple invocations of the
jtulach@1280
   195
     * <tt>initialValue</tt> method in the current thread.
jtulach@1280
   196
     *
jtulach@1280
   197
     * @since 1.5
jtulach@1280
   198
     */
jtulach@1280
   199
     public void remove() {
jtulach@1280
   200
         ThreadLocalMap m = getMap(Thread.currentThread());
jtulach@1280
   201
         if (m != null)
jtulach@1280
   202
             m.remove(this);
jtulach@1280
   203
     }
jtulach@1280
   204
jtulach@1280
   205
    /**
jtulach@1280
   206
     * Get the map associated with a ThreadLocal. Overridden in
jtulach@1280
   207
     * InheritableThreadLocal.
jtulach@1280
   208
     *
jtulach@1280
   209
     * @param  t the current thread
jtulach@1280
   210
     * @return the map
jtulach@1280
   211
     */
jtulach@1280
   212
    ThreadLocalMap getMap(Thread t) {
jtulach@1280
   213
        return t.threadLocals;
jtulach@1280
   214
    }
jtulach@1280
   215
jtulach@1280
   216
    /**
jtulach@1280
   217
     * Create the map associated with a ThreadLocal. Overridden in
jtulach@1280
   218
     * InheritableThreadLocal.
jtulach@1280
   219
     *
jtulach@1280
   220
     * @param t the current thread
jtulach@1280
   221
     * @param firstValue value for the initial entry of the map
jtulach@1280
   222
     * @param map the map to store.
jtulach@1280
   223
     */
jtulach@1280
   224
    void createMap(Thread t, T firstValue) {
jtulach@1280
   225
        t.threadLocals = new ThreadLocalMap(this, firstValue);
jtulach@1280
   226
    }
jtulach@1280
   227
jtulach@1280
   228
    /**
jtulach@1280
   229
     * Factory method to create map of inherited thread locals.
jtulach@1280
   230
     * Designed to be called only from Thread constructor.
jtulach@1280
   231
     *
jtulach@1280
   232
     * @param  parentMap the map associated with parent thread
jtulach@1280
   233
     * @return a map containing the parent's inheritable bindings
jtulach@1280
   234
     */
jtulach@1280
   235
    static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
jtulach@1280
   236
        return new ThreadLocalMap(parentMap);
jtulach@1280
   237
    }
jtulach@1280
   238
jtulach@1280
   239
    /**
jtulach@1280
   240
     * Method childValue is visibly defined in subclass
jtulach@1280
   241
     * InheritableThreadLocal, but is internally defined here for the
jtulach@1280
   242
     * sake of providing createInheritedMap factory method without
jtulach@1280
   243
     * needing to subclass the map class in InheritableThreadLocal.
jtulach@1280
   244
     * This technique is preferable to the alternative of embedding
jtulach@1280
   245
     * instanceof tests in methods.
jtulach@1280
   246
     */
jtulach@1280
   247
    T childValue(T parentValue) {
jtulach@1280
   248
        throw new UnsupportedOperationException();
jtulach@1280
   249
    }
jtulach@1280
   250
jtulach@1280
   251
    /**
jtulach@1280
   252
     * ThreadLocalMap is a customized hash map suitable only for
jtulach@1280
   253
     * maintaining thread local values. No operations are exported
jtulach@1280
   254
     * outside of the ThreadLocal class. The class is package private to
jtulach@1280
   255
     * allow declaration of fields in class Thread.  To help deal with
jtulach@1280
   256
     * very large and long-lived usages, the hash table entries use
jtulach@1280
   257
     * WeakReferences for keys. However, since reference queues are not
jtulach@1280
   258
     * used, stale entries are guaranteed to be removed only when
jtulach@1280
   259
     * the table starts running out of space.
jtulach@1280
   260
     */
jtulach@1280
   261
    static class ThreadLocalMap {
jtulach@1280
   262
jtulach@1280
   263
        /**
jtulach@1280
   264
         * The entries in this hash map extend WeakReference, using
jtulach@1280
   265
         * its main ref field as the key (which is always a
jtulach@1280
   266
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
jtulach@1280
   267
         * == null) mean that the key is no longer referenced, so the
jtulach@1280
   268
         * entry can be expunged from table.  Such entries are referred to
jtulach@1280
   269
         * as "stale entries" in the code that follows.
jtulach@1280
   270
         */
jtulach@1280
   271
        static class Entry extends WeakReference<ThreadLocal> {
jtulach@1280
   272
            /** The value associated with this ThreadLocal. */
jtulach@1280
   273
            Object value;
jtulach@1280
   274
jtulach@1280
   275
            Entry(ThreadLocal k, Object v) {
jtulach@1280
   276
                super(k);
jtulach@1280
   277
                value = v;
jtulach@1280
   278
            }
jtulach@1280
   279
        }
jtulach@1280
   280
jtulach@1280
   281
        /**
jtulach@1280
   282
         * The initial capacity -- MUST be a power of two.
jtulach@1280
   283
         */
jtulach@1280
   284
        private static final int INITIAL_CAPACITY = 16;
jtulach@1280
   285
jtulach@1280
   286
        /**
jtulach@1280
   287
         * The table, resized as necessary.
jtulach@1280
   288
         * table.length MUST always be a power of two.
jtulach@1280
   289
         */
jtulach@1280
   290
        private Entry[] table;
jtulach@1280
   291
jtulach@1280
   292
        /**
jtulach@1280
   293
         * The number of entries in the table.
jtulach@1280
   294
         */
jtulach@1280
   295
        private int size = 0;
jtulach@1280
   296
jtulach@1280
   297
        /**
jtulach@1280
   298
         * The next size value at which to resize.
jtulach@1280
   299
         */
jtulach@1280
   300
        private int threshold; // Default to 0
jtulach@1280
   301
jtulach@1280
   302
        /**
jtulach@1280
   303
         * Set the resize threshold to maintain at worst a 2/3 load factor.
jtulach@1280
   304
         */
jtulach@1280
   305
        private void setThreshold(int len) {
jtulach@1280
   306
            threshold = len * 2 / 3;
jtulach@1280
   307
        }
jtulach@1280
   308
jtulach@1280
   309
        /**
jtulach@1280
   310
         * Increment i modulo len.
jtulach@1280
   311
         */
jtulach@1280
   312
        private static int nextIndex(int i, int len) {
jtulach@1280
   313
            return ((i + 1 < len) ? i + 1 : 0);
jtulach@1280
   314
        }
jtulach@1280
   315
jtulach@1280
   316
        /**
jtulach@1280
   317
         * Decrement i modulo len.
jtulach@1280
   318
         */
jtulach@1280
   319
        private static int prevIndex(int i, int len) {
jtulach@1280
   320
            return ((i - 1 >= 0) ? i - 1 : len - 1);
jtulach@1280
   321
        }
jtulach@1280
   322
jtulach@1280
   323
        /**
jtulach@1280
   324
         * Construct a new map initially containing (firstKey, firstValue).
jtulach@1280
   325
         * ThreadLocalMaps are constructed lazily, so we only create
jtulach@1280
   326
         * one when we have at least one entry to put in it.
jtulach@1280
   327
         */
jtulach@1280
   328
        ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
jtulach@1280
   329
            table = new Entry[INITIAL_CAPACITY];
jtulach@1280
   330
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
jtulach@1280
   331
            table[i] = new Entry(firstKey, firstValue);
jtulach@1280
   332
            size = 1;
jtulach@1280
   333
            setThreshold(INITIAL_CAPACITY);
jtulach@1280
   334
        }
jtulach@1280
   335
jtulach@1280
   336
        /**
jtulach@1280
   337
         * Construct a new map including all Inheritable ThreadLocals
jtulach@1280
   338
         * from given parent map. Called only by createInheritedMap.
jtulach@1280
   339
         *
jtulach@1280
   340
         * @param parentMap the map associated with parent thread.
jtulach@1280
   341
         */
jtulach@1280
   342
        private ThreadLocalMap(ThreadLocalMap parentMap) {
jtulach@1280
   343
            Entry[] parentTable = parentMap.table;
jtulach@1280
   344
            int len = parentTable.length;
jtulach@1280
   345
            setThreshold(len);
jtulach@1280
   346
            table = new Entry[len];
jtulach@1280
   347
jtulach@1280
   348
            for (int j = 0; j < len; j++) {
jtulach@1280
   349
                Entry e = parentTable[j];
jtulach@1280
   350
                if (e != null) {
jtulach@1280
   351
                    ThreadLocal key = e.get();
jtulach@1280
   352
                    if (key != null) {
jtulach@1280
   353
                        Object value = key.childValue(e.value);
jtulach@1280
   354
                        Entry c = new Entry(key, value);
jtulach@1280
   355
                        int h = key.threadLocalHashCode & (len - 1);
jtulach@1280
   356
                        while (table[h] != null)
jtulach@1280
   357
                            h = nextIndex(h, len);
jtulach@1280
   358
                        table[h] = c;
jtulach@1280
   359
                        size++;
jtulach@1280
   360
                    }
jtulach@1280
   361
                }
jtulach@1280
   362
            }
jtulach@1280
   363
        }
jtulach@1280
   364
jtulach@1280
   365
        /**
jtulach@1280
   366
         * Get the entry associated with key.  This method
jtulach@1280
   367
         * itself handles only the fast path: a direct hit of existing
jtulach@1280
   368
         * key. It otherwise relays to getEntryAfterMiss.  This is
jtulach@1280
   369
         * designed to maximize performance for direct hits, in part
jtulach@1280
   370
         * by making this method readily inlinable.
jtulach@1280
   371
         *
jtulach@1280
   372
         * @param  key the thread local object
jtulach@1280
   373
         * @return the entry associated with key, or null if no such
jtulach@1280
   374
         */
jtulach@1280
   375
        private Entry getEntry(ThreadLocal key) {
jtulach@1280
   376
            int i = key.threadLocalHashCode & (table.length - 1);
jtulach@1280
   377
            Entry e = table[i];
jtulach@1280
   378
            if (e != null && e.get() == key)
jtulach@1280
   379
                return e;
jtulach@1280
   380
            else
jtulach@1280
   381
                return getEntryAfterMiss(key, i, e);
jtulach@1280
   382
        }
jtulach@1280
   383
jtulach@1280
   384
        /**
jtulach@1280
   385
         * Version of getEntry method for use when key is not found in
jtulach@1280
   386
         * its direct hash slot.
jtulach@1280
   387
         *
jtulach@1280
   388
         * @param  key the thread local object
jtulach@1280
   389
         * @param  i the table index for key's hash code
jtulach@1280
   390
         * @param  e the entry at table[i]
jtulach@1280
   391
         * @return the entry associated with key, or null if no such
jtulach@1280
   392
         */
jtulach@1280
   393
        private Entry getEntryAfterMiss(ThreadLocal key, int i, Entry e) {
jtulach@1280
   394
            Entry[] tab = table;
jtulach@1280
   395
            int len = tab.length;
jtulach@1280
   396
jtulach@1280
   397
            while (e != null) {
jtulach@1280
   398
                ThreadLocal k = e.get();
jtulach@1280
   399
                if (k == key)
jtulach@1280
   400
                    return e;
jtulach@1280
   401
                if (k == null)
jtulach@1280
   402
                    expungeStaleEntry(i);
jtulach@1280
   403
                else
jtulach@1280
   404
                    i = nextIndex(i, len);
jtulach@1280
   405
                e = tab[i];
jtulach@1280
   406
            }
jtulach@1280
   407
            return null;
jtulach@1280
   408
        }
jtulach@1280
   409
jtulach@1280
   410
        /**
jtulach@1280
   411
         * Set the value associated with key.
jtulach@1280
   412
         *
jtulach@1280
   413
         * @param key the thread local object
jtulach@1280
   414
         * @param value the value to be set
jtulach@1280
   415
         */
jtulach@1280
   416
        private void set(ThreadLocal key, Object value) {
jtulach@1280
   417
jtulach@1280
   418
            // We don't use a fast path as with get() because it is at
jtulach@1280
   419
            // least as common to use set() to create new entries as
jtulach@1280
   420
            // it is to replace existing ones, in which case, a fast
jtulach@1280
   421
            // path would fail more often than not.
jtulach@1280
   422
jtulach@1280
   423
            Entry[] tab = table;
jtulach@1280
   424
            int len = tab.length;
jtulach@1280
   425
            int i = key.threadLocalHashCode & (len-1);
jtulach@1280
   426
jtulach@1280
   427
            for (Entry e = tab[i];
jtulach@1280
   428
                 e != null;
jtulach@1280
   429
                 e = tab[i = nextIndex(i, len)]) {
jtulach@1280
   430
                ThreadLocal k = e.get();
jtulach@1280
   431
jtulach@1280
   432
                if (k == key) {
jtulach@1280
   433
                    e.value = value;
jtulach@1280
   434
                    return;
jtulach@1280
   435
                }
jtulach@1280
   436
jtulach@1280
   437
                if (k == null) {
jtulach@1280
   438
                    replaceStaleEntry(key, value, i);
jtulach@1280
   439
                    return;
jtulach@1280
   440
                }
jtulach@1280
   441
            }
jtulach@1280
   442
jtulach@1280
   443
            tab[i] = new Entry(key, value);
jtulach@1280
   444
            int sz = ++size;
jtulach@1280
   445
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
jtulach@1280
   446
                rehash();
jtulach@1280
   447
        }
jtulach@1280
   448
jtulach@1280
   449
        /**
jtulach@1280
   450
         * Remove the entry for key.
jtulach@1280
   451
         */
jtulach@1280
   452
        private void remove(ThreadLocal key) {
jtulach@1280
   453
            Entry[] tab = table;
jtulach@1280
   454
            int len = tab.length;
jtulach@1280
   455
            int i = key.threadLocalHashCode & (len-1);
jtulach@1280
   456
            for (Entry e = tab[i];
jtulach@1280
   457
                 e != null;
jtulach@1280
   458
                 e = tab[i = nextIndex(i, len)]) {
jtulach@1280
   459
                if (e.get() == key) {
jtulach@1280
   460
                    e.clear();
jtulach@1280
   461
                    expungeStaleEntry(i);
jtulach@1280
   462
                    return;
jtulach@1280
   463
                }
jtulach@1280
   464
            }
jtulach@1280
   465
        }
jtulach@1280
   466
jtulach@1280
   467
        /**
jtulach@1280
   468
         * Replace a stale entry encountered during a set operation
jtulach@1280
   469
         * with an entry for the specified key.  The value passed in
jtulach@1280
   470
         * the value parameter is stored in the entry, whether or not
jtulach@1280
   471
         * an entry already exists for the specified key.
jtulach@1280
   472
         *
jtulach@1280
   473
         * As a side effect, this method expunges all stale entries in the
jtulach@1280
   474
         * "run" containing the stale entry.  (A run is a sequence of entries
jtulach@1280
   475
         * between two null slots.)
jtulach@1280
   476
         *
jtulach@1280
   477
         * @param  key the key
jtulach@1280
   478
         * @param  value the value to be associated with key
jtulach@1280
   479
         * @param  staleSlot index of the first stale entry encountered while
jtulach@1280
   480
         *         searching for key.
jtulach@1280
   481
         */
jtulach@1280
   482
        private void replaceStaleEntry(ThreadLocal key, Object value,
jtulach@1280
   483
                                       int staleSlot) {
jtulach@1280
   484
            Entry[] tab = table;
jtulach@1280
   485
            int len = tab.length;
jtulach@1280
   486
            Entry e;
jtulach@1280
   487
jtulach@1280
   488
            // Back up to check for prior stale entry in current run.
jtulach@1280
   489
            // We clean out whole runs at a time to avoid continual
jtulach@1280
   490
            // incremental rehashing due to garbage collector freeing
jtulach@1280
   491
            // up refs in bunches (i.e., whenever the collector runs).
jtulach@1280
   492
            int slotToExpunge = staleSlot;
jtulach@1280
   493
            for (int i = prevIndex(staleSlot, len);
jtulach@1280
   494
                 (e = tab[i]) != null;
jtulach@1280
   495
                 i = prevIndex(i, len))
jtulach@1280
   496
                if (e.get() == null)
jtulach@1280
   497
                    slotToExpunge = i;
jtulach@1280
   498
jtulach@1280
   499
            // Find either the key or trailing null slot of run, whichever
jtulach@1280
   500
            // occurs first
jtulach@1280
   501
            for (int i = nextIndex(staleSlot, len);
jtulach@1280
   502
                 (e = tab[i]) != null;
jtulach@1280
   503
                 i = nextIndex(i, len)) {
jtulach@1280
   504
                ThreadLocal k = e.get();
jtulach@1280
   505
jtulach@1280
   506
                // If we find key, then we need to swap it
jtulach@1280
   507
                // with the stale entry to maintain hash table order.
jtulach@1280
   508
                // The newly stale slot, or any other stale slot
jtulach@1280
   509
                // encountered above it, can then be sent to expungeStaleEntry
jtulach@1280
   510
                // to remove or rehash all of the other entries in run.
jtulach@1280
   511
                if (k == key) {
jtulach@1280
   512
                    e.value = value;
jtulach@1280
   513
jtulach@1280
   514
                    tab[i] = tab[staleSlot];
jtulach@1280
   515
                    tab[staleSlot] = e;
jtulach@1280
   516
jtulach@1280
   517
                    // Start expunge at preceding stale entry if it exists
jtulach@1280
   518
                    if (slotToExpunge == staleSlot)
jtulach@1280
   519
                        slotToExpunge = i;
jtulach@1280
   520
                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
jtulach@1280
   521
                    return;
jtulach@1280
   522
                }
jtulach@1280
   523
jtulach@1280
   524
                // If we didn't find stale entry on backward scan, the
jtulach@1280
   525
                // first stale entry seen while scanning for key is the
jtulach@1280
   526
                // first still present in the run.
jtulach@1280
   527
                if (k == null && slotToExpunge == staleSlot)
jtulach@1280
   528
                    slotToExpunge = i;
jtulach@1280
   529
            }
jtulach@1280
   530
jtulach@1280
   531
            // If key not found, put new entry in stale slot
jtulach@1280
   532
            tab[staleSlot].value = null;
jtulach@1280
   533
            tab[staleSlot] = new Entry(key, value);
jtulach@1280
   534
jtulach@1280
   535
            // If there are any other stale entries in run, expunge them
jtulach@1280
   536
            if (slotToExpunge != staleSlot)
jtulach@1280
   537
                cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
jtulach@1280
   538
        }
jtulach@1280
   539
jtulach@1280
   540
        /**
jtulach@1280
   541
         * Expunge a stale entry by rehashing any possibly colliding entries
jtulach@1280
   542
         * lying between staleSlot and the next null slot.  This also expunges
jtulach@1280
   543
         * any other stale entries encountered before the trailing null.  See
jtulach@1280
   544
         * Knuth, Section 6.4
jtulach@1280
   545
         *
jtulach@1280
   546
         * @param staleSlot index of slot known to have null key
jtulach@1280
   547
         * @return the index of the next null slot after staleSlot
jtulach@1280
   548
         * (all between staleSlot and this slot will have been checked
jtulach@1280
   549
         * for expunging).
jtulach@1280
   550
         */
jtulach@1280
   551
        private int expungeStaleEntry(int staleSlot) {
jtulach@1280
   552
            Entry[] tab = table;
jtulach@1280
   553
            int len = tab.length;
jtulach@1280
   554
jtulach@1280
   555
            // expunge entry at staleSlot
jtulach@1280
   556
            tab[staleSlot].value = null;
jtulach@1280
   557
            tab[staleSlot] = null;
jtulach@1280
   558
            size--;
jtulach@1280
   559
jtulach@1280
   560
            // Rehash until we encounter null
jtulach@1280
   561
            Entry e;
jtulach@1280
   562
            int i;
jtulach@1280
   563
            for (i = nextIndex(staleSlot, len);
jtulach@1280
   564
                 (e = tab[i]) != null;
jtulach@1280
   565
                 i = nextIndex(i, len)) {
jtulach@1280
   566
                ThreadLocal k = e.get();
jtulach@1280
   567
                if (k == null) {
jtulach@1280
   568
                    e.value = null;
jtulach@1280
   569
                    tab[i] = null;
jtulach@1280
   570
                    size--;
jtulach@1280
   571
                } else {
jtulach@1280
   572
                    int h = k.threadLocalHashCode & (len - 1);
jtulach@1280
   573
                    if (h != i) {
jtulach@1280
   574
                        tab[i] = null;
jtulach@1280
   575
jtulach@1280
   576
                        // Unlike Knuth 6.4 Algorithm R, we must scan until
jtulach@1280
   577
                        // null because multiple entries could have been stale.
jtulach@1280
   578
                        while (tab[h] != null)
jtulach@1280
   579
                            h = nextIndex(h, len);
jtulach@1280
   580
                        tab[h] = e;
jtulach@1280
   581
                    }
jtulach@1280
   582
                }
jtulach@1280
   583
            }
jtulach@1280
   584
            return i;
jtulach@1280
   585
        }
jtulach@1280
   586
jtulach@1280
   587
        /**
jtulach@1280
   588
         * Heuristically scan some cells looking for stale entries.
jtulach@1280
   589
         * This is invoked when either a new element is added, or
jtulach@1280
   590
         * another stale one has been expunged. It performs a
jtulach@1280
   591
         * logarithmic number of scans, as a balance between no
jtulach@1280
   592
         * scanning (fast but retains garbage) and a number of scans
jtulach@1280
   593
         * proportional to number of elements, that would find all
jtulach@1280
   594
         * garbage but would cause some insertions to take O(n) time.
jtulach@1280
   595
         *
jtulach@1280
   596
         * @param i a position known NOT to hold a stale entry. The
jtulach@1280
   597
         * scan starts at the element after i.
jtulach@1280
   598
         *
jtulach@1280
   599
         * @param n scan control: <tt>log2(n)</tt> cells are scanned,
jtulach@1280
   600
         * unless a stale entry is found, in which case
jtulach@1280
   601
         * <tt>log2(table.length)-1</tt> additional cells are scanned.
jtulach@1280
   602
         * When called from insertions, this parameter is the number
jtulach@1280
   603
         * of elements, but when from replaceStaleEntry, it is the
jtulach@1280
   604
         * table length. (Note: all this could be changed to be either
jtulach@1280
   605
         * more or less aggressive by weighting n instead of just
jtulach@1280
   606
         * using straight log n. But this version is simple, fast, and
jtulach@1280
   607
         * seems to work well.)
jtulach@1280
   608
         *
jtulach@1280
   609
         * @return true if any stale entries have been removed.
jtulach@1280
   610
         */
jtulach@1280
   611
        private boolean cleanSomeSlots(int i, int n) {
jtulach@1280
   612
            boolean removed = false;
jtulach@1280
   613
            Entry[] tab = table;
jtulach@1280
   614
            int len = tab.length;
jtulach@1280
   615
            do {
jtulach@1280
   616
                i = nextIndex(i, len);
jtulach@1280
   617
                Entry e = tab[i];
jtulach@1280
   618
                if (e != null && e.get() == null) {
jtulach@1280
   619
                    n = len;
jtulach@1280
   620
                    removed = true;
jtulach@1280
   621
                    i = expungeStaleEntry(i);
jtulach@1280
   622
                }
jtulach@1280
   623
            } while ( (n >>>= 1) != 0);
jtulach@1280
   624
            return removed;
jtulach@1280
   625
        }
jtulach@1280
   626
jtulach@1280
   627
        /**
jtulach@1280
   628
         * Re-pack and/or re-size the table. First scan the entire
jtulach@1280
   629
         * table removing stale entries. If this doesn't sufficiently
jtulach@1280
   630
         * shrink the size of the table, double the table size.
jtulach@1280
   631
         */
jtulach@1280
   632
        private void rehash() {
jtulach@1280
   633
            expungeStaleEntries();
jtulach@1280
   634
jtulach@1280
   635
            // Use lower threshold for doubling to avoid hysteresis
jtulach@1280
   636
            if (size >= threshold - threshold / 4)
jtulach@1280
   637
                resize();
jtulach@1280
   638
        }
jtulach@1280
   639
jtulach@1280
   640
        /**
jtulach@1280
   641
         * Double the capacity of the table.
jtulach@1280
   642
         */
jtulach@1280
   643
        private void resize() {
jtulach@1280
   644
            Entry[] oldTab = table;
jtulach@1280
   645
            int oldLen = oldTab.length;
jtulach@1280
   646
            int newLen = oldLen * 2;
jtulach@1280
   647
            Entry[] newTab = new Entry[newLen];
jtulach@1280
   648
            int count = 0;
jtulach@1280
   649
jtulach@1280
   650
            for (int j = 0; j < oldLen; ++j) {
jtulach@1280
   651
                Entry e = oldTab[j];
jtulach@1280
   652
                if (e != null) {
jtulach@1280
   653
                    ThreadLocal k = e.get();
jtulach@1280
   654
                    if (k == null) {
jtulach@1280
   655
                        e.value = null; // Help the GC
jtulach@1280
   656
                    } else {
jtulach@1280
   657
                        int h = k.threadLocalHashCode & (newLen - 1);
jtulach@1280
   658
                        while (newTab[h] != null)
jtulach@1280
   659
                            h = nextIndex(h, newLen);
jtulach@1280
   660
                        newTab[h] = e;
jtulach@1280
   661
                        count++;
jtulach@1280
   662
                    }
jtulach@1280
   663
                }
jtulach@1280
   664
            }
jtulach@1280
   665
jtulach@1280
   666
            setThreshold(newLen);
jtulach@1280
   667
            size = count;
jtulach@1280
   668
            table = newTab;
jtulach@1280
   669
        }
jtulach@1280
   670
jtulach@1280
   671
        /**
jtulach@1280
   672
         * Expunge all stale entries in the table.
jtulach@1280
   673
         */
jtulach@1280
   674
        private void expungeStaleEntries() {
jtulach@1280
   675
            Entry[] tab = table;
jtulach@1280
   676
            int len = tab.length;
jtulach@1280
   677
            for (int j = 0; j < len; j++) {
jtulach@1280
   678
                Entry e = tab[j];
jtulach@1280
   679
                if (e != null && e.get() == null)
jtulach@1280
   680
                    expungeStaleEntry(j);
jtulach@1280
   681
            }
jtulach@1280
   682
        }
jtulach@1280
   683
    }
jtulach@1280
   684
}