jtulach@1280: /* jtulach@1280: * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. jtulach@1280: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jtulach@1280: * jtulach@1280: * This code is free software; you can redistribute it and/or modify it jtulach@1280: * under the terms of the GNU General Public License version 2 only, as jtulach@1280: * published by the Free Software Foundation. Oracle designates this jtulach@1280: * particular file as subject to the "Classpath" exception as provided jtulach@1280: * by Oracle in the LICENSE file that accompanied this code. jtulach@1280: * jtulach@1280: * This code is distributed in the hope that it will be useful, but WITHOUT jtulach@1280: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jtulach@1280: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jtulach@1280: * version 2 for more details (a copy is included in the LICENSE file that jtulach@1280: * accompanied this code). jtulach@1280: * jtulach@1280: * You should have received a copy of the GNU General Public License version jtulach@1280: * 2 along with this work; if not, write to the Free Software Foundation, jtulach@1280: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jtulach@1280: * jtulach@1280: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jtulach@1280: * or visit www.oracle.com if you need additional information or have any jtulach@1280: * questions. jtulach@1280: */ jtulach@1280: jtulach@1280: package java.lang; jtulach@1280: import java.lang.ref.*; jtulach@1280: import java.util.concurrent.atomic.AtomicInteger; jtulach@1280: jtulach@1280: /** jtulach@1280: * This class provides thread-local variables. These variables differ from jtulach@1280: * their normal counterparts in that each thread that accesses one (via its jtulach@1280: * get or set method) has its own, independently initialized jtulach@1280: * copy of the variable. ThreadLocal instances are typically private jtulach@1280: * static fields in classes that wish to associate state with a thread (e.g., jtulach@1280: * a user ID or Transaction ID). jtulach@1280: * jtulach@1280: *

For example, the class below generates unique identifiers local to each jtulach@1280: * thread. jtulach@1280: * A thread's id is assigned the first time it invokes ThreadId.get() jtulach@1280: * and remains unchanged on subsequent calls. jtulach@1280: *

jtulach@1280:  * import java.util.concurrent.atomic.AtomicInteger;
jtulach@1280:  *
jtulach@1280:  * public class ThreadId {
jtulach@1280:  *     // Atomic integer containing the next thread ID to be assigned
jtulach@1280:  *     private static final AtomicInteger nextId = new AtomicInteger(0);
jtulach@1280:  *
jtulach@1280:  *     // Thread local variable containing each thread's ID
jtulach@1280:  *     private static final ThreadLocal<Integer> threadId =
jtulach@1280:  *         new ThreadLocal<Integer>() {
jtulach@1280:  *             @Override protected Integer initialValue() {
jtulach@1280:  *                 return nextId.getAndIncrement();
jtulach@1280:  *         }
jtulach@1280:  *     };
jtulach@1280:  *
jtulach@1280:  *     // Returns the current thread's unique ID, assigning it if necessary
jtulach@1280:  *     public static int get() {
jtulach@1280:  *         return threadId.get();
jtulach@1280:  *     }
jtulach@1280:  * }
jtulach@1280:  * 
jtulach@1280: *

Each thread holds an implicit reference to its copy of a thread-local jtulach@1280: * variable as long as the thread is alive and the ThreadLocal jtulach@1280: * instance is accessible; after a thread goes away, all of its copies of jtulach@1280: * thread-local instances are subject to garbage collection (unless other jtulach@1280: * references to these copies exist). jtulach@1280: * jtulach@1280: * @author Josh Bloch and Doug Lea jtulach@1280: * @since 1.2 jtulach@1280: */ jtulach@1280: public class ThreadLocal { jtulach@1280: /** jtulach@1280: * ThreadLocals rely on per-thread linear-probe hash maps attached jtulach@1280: * to each thread (Thread.threadLocals and jtulach@1280: * inheritableThreadLocals). The ThreadLocal objects act as keys, jtulach@1280: * searched via threadLocalHashCode. This is a custom hash code jtulach@1280: * (useful only within ThreadLocalMaps) that eliminates collisions jtulach@1280: * in the common case where consecutively constructed ThreadLocals jtulach@1280: * are used by the same threads, while remaining well-behaved in jtulach@1280: * less common cases. jtulach@1280: */ jtulach@1280: private final int threadLocalHashCode = nextHashCode(); jtulach@1280: jtulach@1280: /** jtulach@1280: * The next hash code to be given out. Updated atomically. Starts at jtulach@1280: * zero. jtulach@1280: */ jtulach@1280: private static AtomicInteger nextHashCode = jtulach@1280: new AtomicInteger(); jtulach@1280: jtulach@1280: /** jtulach@1280: * The difference between successively generated hash codes - turns jtulach@1280: * implicit sequential thread-local IDs into near-optimally spread jtulach@1280: * multiplicative hash values for power-of-two-sized tables. jtulach@1280: */ jtulach@1280: private static final int HASH_INCREMENT = 0x61c88647; jtulach@1280: jtulach@1280: /** jtulach@1280: * Returns the next hash code. jtulach@1280: */ jtulach@1280: private static int nextHashCode() { jtulach@1280: return nextHashCode.getAndAdd(HASH_INCREMENT); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Returns the current thread's "initial value" for this jtulach@1280: * thread-local variable. This method will be invoked the first jtulach@1280: * time a thread accesses the variable with the {@link #get} jtulach@1280: * method, unless the thread previously invoked the {@link #set} jtulach@1280: * method, in which case the initialValue method will not jtulach@1280: * be invoked for the thread. Normally, this method is invoked at jtulach@1280: * most once per thread, but it may be invoked again in case of jtulach@1280: * subsequent invocations of {@link #remove} followed by {@link #get}. jtulach@1280: * jtulach@1280: *

This implementation simply returns null; if the jtulach@1280: * programmer desires thread-local variables to have an initial jtulach@1280: * value other than null, ThreadLocal must be jtulach@1280: * subclassed, and this method overridden. Typically, an jtulach@1280: * anonymous inner class will be used. jtulach@1280: * jtulach@1280: * @return the initial value for this thread-local jtulach@1280: */ jtulach@1280: protected T initialValue() { jtulach@1280: return null; jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Creates a thread local variable. jtulach@1280: */ jtulach@1280: public ThreadLocal() { jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Returns the value in the current thread's copy of this jtulach@1280: * thread-local variable. If the variable has no value for the jtulach@1280: * current thread, it is first initialized to the value returned jtulach@1280: * by an invocation of the {@link #initialValue} method. jtulach@1280: * jtulach@1280: * @return the current thread's value of this thread-local jtulach@1280: */ jtulach@1280: public T get() { jtulach@1280: Thread t = Thread.currentThread(); jtulach@1280: ThreadLocalMap map = getMap(t); jtulach@1280: if (map != null) { jtulach@1280: ThreadLocalMap.Entry e = map.getEntry(this); jtulach@1280: if (e != null) jtulach@1280: return (T)e.value; jtulach@1280: } jtulach@1280: return setInitialValue(); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Variant of set() to establish initialValue. Used instead jtulach@1280: * of set() in case user has overridden the set() method. jtulach@1280: * jtulach@1280: * @return the initial value jtulach@1280: */ jtulach@1280: private T setInitialValue() { jtulach@1280: T value = initialValue(); jtulach@1280: Thread t = Thread.currentThread(); jtulach@1280: ThreadLocalMap map = getMap(t); jtulach@1280: if (map != null) jtulach@1280: map.set(this, value); jtulach@1280: else jtulach@1280: createMap(t, value); jtulach@1280: return value; jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Sets the current thread's copy of this thread-local variable jtulach@1280: * to the specified value. Most subclasses will have no need to jtulach@1280: * override this method, relying solely on the {@link #initialValue} jtulach@1280: * method to set the values of thread-locals. jtulach@1280: * jtulach@1280: * @param value the value to be stored in the current thread's copy of jtulach@1280: * this thread-local. jtulach@1280: */ jtulach@1280: public void set(T value) { jtulach@1280: Thread t = Thread.currentThread(); jtulach@1280: ThreadLocalMap map = getMap(t); jtulach@1280: if (map != null) jtulach@1280: map.set(this, value); jtulach@1280: else jtulach@1280: createMap(t, value); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Removes the current thread's value for this thread-local jtulach@1280: * variable. If this thread-local variable is subsequently jtulach@1280: * {@linkplain #get read} by the current thread, its value will be jtulach@1280: * reinitialized by invoking its {@link #initialValue} method, jtulach@1280: * unless its value is {@linkplain #set set} by the current thread jtulach@1280: * in the interim. This may result in multiple invocations of the jtulach@1280: * initialValue method in the current thread. jtulach@1280: * jtulach@1280: * @since 1.5 jtulach@1280: */ jtulach@1280: public void remove() { jtulach@1280: ThreadLocalMap m = getMap(Thread.currentThread()); jtulach@1280: if (m != null) jtulach@1280: m.remove(this); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Get the map associated with a ThreadLocal. Overridden in jtulach@1280: * InheritableThreadLocal. jtulach@1280: * jtulach@1280: * @param t the current thread jtulach@1280: * @return the map jtulach@1280: */ jtulach@1280: ThreadLocalMap getMap(Thread t) { jtulach@1280: return t.threadLocals; jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Create the map associated with a ThreadLocal. Overridden in jtulach@1280: * InheritableThreadLocal. jtulach@1280: * jtulach@1280: * @param t the current thread jtulach@1280: * @param firstValue value for the initial entry of the map jtulach@1280: * @param map the map to store. jtulach@1280: */ jtulach@1280: void createMap(Thread t, T firstValue) { jtulach@1280: t.threadLocals = new ThreadLocalMap(this, firstValue); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Factory method to create map of inherited thread locals. jtulach@1280: * Designed to be called only from Thread constructor. jtulach@1280: * jtulach@1280: * @param parentMap the map associated with parent thread jtulach@1280: * @return a map containing the parent's inheritable bindings jtulach@1280: */ jtulach@1280: static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) { jtulach@1280: return new ThreadLocalMap(parentMap); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Method childValue is visibly defined in subclass jtulach@1280: * InheritableThreadLocal, but is internally defined here for the jtulach@1280: * sake of providing createInheritedMap factory method without jtulach@1280: * needing to subclass the map class in InheritableThreadLocal. jtulach@1280: * This technique is preferable to the alternative of embedding jtulach@1280: * instanceof tests in methods. jtulach@1280: */ jtulach@1280: T childValue(T parentValue) { jtulach@1280: throw new UnsupportedOperationException(); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * ThreadLocalMap is a customized hash map suitable only for jtulach@1280: * maintaining thread local values. No operations are exported jtulach@1280: * outside of the ThreadLocal class. The class is package private to jtulach@1280: * allow declaration of fields in class Thread. To help deal with jtulach@1280: * very large and long-lived usages, the hash table entries use jtulach@1280: * WeakReferences for keys. However, since reference queues are not jtulach@1280: * used, stale entries are guaranteed to be removed only when jtulach@1280: * the table starts running out of space. jtulach@1280: */ jtulach@1280: static class ThreadLocalMap { jtulach@1280: jtulach@1280: /** jtulach@1280: * The entries in this hash map extend WeakReference, using jtulach@1280: * its main ref field as the key (which is always a jtulach@1280: * ThreadLocal object). Note that null keys (i.e. entry.get() jtulach@1280: * == null) mean that the key is no longer referenced, so the jtulach@1280: * entry can be expunged from table. Such entries are referred to jtulach@1280: * as "stale entries" in the code that follows. jtulach@1280: */ jtulach@1280: static class Entry extends WeakReference { jtulach@1280: /** The value associated with this ThreadLocal. */ jtulach@1280: Object value; jtulach@1280: jtulach@1280: Entry(ThreadLocal k, Object v) { jtulach@1280: super(k); jtulach@1280: value = v; jtulach@1280: } jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * The initial capacity -- MUST be a power of two. jtulach@1280: */ jtulach@1280: private static final int INITIAL_CAPACITY = 16; jtulach@1280: jtulach@1280: /** jtulach@1280: * The table, resized as necessary. jtulach@1280: * table.length MUST always be a power of two. jtulach@1280: */ jtulach@1280: private Entry[] table; jtulach@1280: jtulach@1280: /** jtulach@1280: * The number of entries in the table. jtulach@1280: */ jtulach@1280: private int size = 0; jtulach@1280: jtulach@1280: /** jtulach@1280: * The next size value at which to resize. jtulach@1280: */ jtulach@1280: private int threshold; // Default to 0 jtulach@1280: jtulach@1280: /** jtulach@1280: * Set the resize threshold to maintain at worst a 2/3 load factor. jtulach@1280: */ jtulach@1280: private void setThreshold(int len) { jtulach@1280: threshold = len * 2 / 3; jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Increment i modulo len. jtulach@1280: */ jtulach@1280: private static int nextIndex(int i, int len) { jtulach@1280: return ((i + 1 < len) ? i + 1 : 0); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Decrement i modulo len. jtulach@1280: */ jtulach@1280: private static int prevIndex(int i, int len) { jtulach@1280: return ((i - 1 >= 0) ? i - 1 : len - 1); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Construct a new map initially containing (firstKey, firstValue). jtulach@1280: * ThreadLocalMaps are constructed lazily, so we only create jtulach@1280: * one when we have at least one entry to put in it. jtulach@1280: */ jtulach@1280: ThreadLocalMap(ThreadLocal firstKey, Object firstValue) { jtulach@1280: table = new Entry[INITIAL_CAPACITY]; jtulach@1280: int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); jtulach@1280: table[i] = new Entry(firstKey, firstValue); jtulach@1280: size = 1; jtulach@1280: setThreshold(INITIAL_CAPACITY); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Construct a new map including all Inheritable ThreadLocals jtulach@1280: * from given parent map. Called only by createInheritedMap. jtulach@1280: * jtulach@1280: * @param parentMap the map associated with parent thread. jtulach@1280: */ jtulach@1280: private ThreadLocalMap(ThreadLocalMap parentMap) { jtulach@1280: Entry[] parentTable = parentMap.table; jtulach@1280: int len = parentTable.length; jtulach@1280: setThreshold(len); jtulach@1280: table = new Entry[len]; jtulach@1280: jtulach@1280: for (int j = 0; j < len; j++) { jtulach@1280: Entry e = parentTable[j]; jtulach@1280: if (e != null) { jtulach@1280: ThreadLocal key = e.get(); jtulach@1280: if (key != null) { jtulach@1280: Object value = key.childValue(e.value); jtulach@1280: Entry c = new Entry(key, value); jtulach@1280: int h = key.threadLocalHashCode & (len - 1); jtulach@1280: while (table[h] != null) jtulach@1280: h = nextIndex(h, len); jtulach@1280: table[h] = c; jtulach@1280: size++; jtulach@1280: } jtulach@1280: } jtulach@1280: } jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Get the entry associated with key. This method jtulach@1280: * itself handles only the fast path: a direct hit of existing jtulach@1280: * key. It otherwise relays to getEntryAfterMiss. This is jtulach@1280: * designed to maximize performance for direct hits, in part jtulach@1280: * by making this method readily inlinable. jtulach@1280: * jtulach@1280: * @param key the thread local object jtulach@1280: * @return the entry associated with key, or null if no such jtulach@1280: */ jtulach@1280: private Entry getEntry(ThreadLocal key) { jtulach@1280: int i = key.threadLocalHashCode & (table.length - 1); jtulach@1280: Entry e = table[i]; jtulach@1280: if (e != null && e.get() == key) jtulach@1280: return e; jtulach@1280: else jtulach@1280: return getEntryAfterMiss(key, i, e); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Version of getEntry method for use when key is not found in jtulach@1280: * its direct hash slot. jtulach@1280: * jtulach@1280: * @param key the thread local object jtulach@1280: * @param i the table index for key's hash code jtulach@1280: * @param e the entry at table[i] jtulach@1280: * @return the entry associated with key, or null if no such jtulach@1280: */ jtulach@1280: private Entry getEntryAfterMiss(ThreadLocal key, int i, Entry e) { jtulach@1280: Entry[] tab = table; jtulach@1280: int len = tab.length; jtulach@1280: jtulach@1280: while (e != null) { jtulach@1280: ThreadLocal k = e.get(); jtulach@1280: if (k == key) jtulach@1280: return e; jtulach@1280: if (k == null) jtulach@1280: expungeStaleEntry(i); jtulach@1280: else jtulach@1280: i = nextIndex(i, len); jtulach@1280: e = tab[i]; jtulach@1280: } jtulach@1280: return null; jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Set the value associated with key. jtulach@1280: * jtulach@1280: * @param key the thread local object jtulach@1280: * @param value the value to be set jtulach@1280: */ jtulach@1280: private void set(ThreadLocal key, Object value) { jtulach@1280: jtulach@1280: // We don't use a fast path as with get() because it is at jtulach@1280: // least as common to use set() to create new entries as jtulach@1280: // it is to replace existing ones, in which case, a fast jtulach@1280: // path would fail more often than not. jtulach@1280: jtulach@1280: Entry[] tab = table; jtulach@1280: int len = tab.length; jtulach@1280: int i = key.threadLocalHashCode & (len-1); jtulach@1280: jtulach@1280: for (Entry e = tab[i]; jtulach@1280: e != null; jtulach@1280: e = tab[i = nextIndex(i, len)]) { jtulach@1280: ThreadLocal k = e.get(); jtulach@1280: jtulach@1280: if (k == key) { jtulach@1280: e.value = value; jtulach@1280: return; jtulach@1280: } jtulach@1280: jtulach@1280: if (k == null) { jtulach@1280: replaceStaleEntry(key, value, i); jtulach@1280: return; jtulach@1280: } jtulach@1280: } jtulach@1280: jtulach@1280: tab[i] = new Entry(key, value); jtulach@1280: int sz = ++size; jtulach@1280: if (!cleanSomeSlots(i, sz) && sz >= threshold) jtulach@1280: rehash(); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Remove the entry for key. jtulach@1280: */ jtulach@1280: private void remove(ThreadLocal key) { jtulach@1280: Entry[] tab = table; jtulach@1280: int len = tab.length; jtulach@1280: int i = key.threadLocalHashCode & (len-1); jtulach@1280: for (Entry e = tab[i]; jtulach@1280: e != null; jtulach@1280: e = tab[i = nextIndex(i, len)]) { jtulach@1280: if (e.get() == key) { jtulach@1280: e.clear(); jtulach@1280: expungeStaleEntry(i); jtulach@1280: return; jtulach@1280: } jtulach@1280: } jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Replace a stale entry encountered during a set operation jtulach@1280: * with an entry for the specified key. The value passed in jtulach@1280: * the value parameter is stored in the entry, whether or not jtulach@1280: * an entry already exists for the specified key. jtulach@1280: * jtulach@1280: * As a side effect, this method expunges all stale entries in the jtulach@1280: * "run" containing the stale entry. (A run is a sequence of entries jtulach@1280: * between two null slots.) jtulach@1280: * jtulach@1280: * @param key the key jtulach@1280: * @param value the value to be associated with key jtulach@1280: * @param staleSlot index of the first stale entry encountered while jtulach@1280: * searching for key. jtulach@1280: */ jtulach@1280: private void replaceStaleEntry(ThreadLocal key, Object value, jtulach@1280: int staleSlot) { jtulach@1280: Entry[] tab = table; jtulach@1280: int len = tab.length; jtulach@1280: Entry e; jtulach@1280: jtulach@1280: // Back up to check for prior stale entry in current run. jtulach@1280: // We clean out whole runs at a time to avoid continual jtulach@1280: // incremental rehashing due to garbage collector freeing jtulach@1280: // up refs in bunches (i.e., whenever the collector runs). jtulach@1280: int slotToExpunge = staleSlot; jtulach@1280: for (int i = prevIndex(staleSlot, len); jtulach@1280: (e = tab[i]) != null; jtulach@1280: i = prevIndex(i, len)) jtulach@1280: if (e.get() == null) jtulach@1280: slotToExpunge = i; jtulach@1280: jtulach@1280: // Find either the key or trailing null slot of run, whichever jtulach@1280: // occurs first jtulach@1280: for (int i = nextIndex(staleSlot, len); jtulach@1280: (e = tab[i]) != null; jtulach@1280: i = nextIndex(i, len)) { jtulach@1280: ThreadLocal k = e.get(); jtulach@1280: jtulach@1280: // If we find key, then we need to swap it jtulach@1280: // with the stale entry to maintain hash table order. jtulach@1280: // The newly stale slot, or any other stale slot jtulach@1280: // encountered above it, can then be sent to expungeStaleEntry jtulach@1280: // to remove or rehash all of the other entries in run. jtulach@1280: if (k == key) { jtulach@1280: e.value = value; jtulach@1280: jtulach@1280: tab[i] = tab[staleSlot]; jtulach@1280: tab[staleSlot] = e; jtulach@1280: jtulach@1280: // Start expunge at preceding stale entry if it exists jtulach@1280: if (slotToExpunge == staleSlot) jtulach@1280: slotToExpunge = i; jtulach@1280: cleanSomeSlots(expungeStaleEntry(slotToExpunge), len); jtulach@1280: return; jtulach@1280: } jtulach@1280: jtulach@1280: // If we didn't find stale entry on backward scan, the jtulach@1280: // first stale entry seen while scanning for key is the jtulach@1280: // first still present in the run. jtulach@1280: if (k == null && slotToExpunge == staleSlot) jtulach@1280: slotToExpunge = i; jtulach@1280: } jtulach@1280: jtulach@1280: // If key not found, put new entry in stale slot jtulach@1280: tab[staleSlot].value = null; jtulach@1280: tab[staleSlot] = new Entry(key, value); jtulach@1280: jtulach@1280: // If there are any other stale entries in run, expunge them jtulach@1280: if (slotToExpunge != staleSlot) jtulach@1280: cleanSomeSlots(expungeStaleEntry(slotToExpunge), len); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Expunge a stale entry by rehashing any possibly colliding entries jtulach@1280: * lying between staleSlot and the next null slot. This also expunges jtulach@1280: * any other stale entries encountered before the trailing null. See jtulach@1280: * Knuth, Section 6.4 jtulach@1280: * jtulach@1280: * @param staleSlot index of slot known to have null key jtulach@1280: * @return the index of the next null slot after staleSlot jtulach@1280: * (all between staleSlot and this slot will have been checked jtulach@1280: * for expunging). jtulach@1280: */ jtulach@1280: private int expungeStaleEntry(int staleSlot) { jtulach@1280: Entry[] tab = table; jtulach@1280: int len = tab.length; jtulach@1280: jtulach@1280: // expunge entry at staleSlot jtulach@1280: tab[staleSlot].value = null; jtulach@1280: tab[staleSlot] = null; jtulach@1280: size--; jtulach@1280: jtulach@1280: // Rehash until we encounter null jtulach@1280: Entry e; jtulach@1280: int i; jtulach@1280: for (i = nextIndex(staleSlot, len); jtulach@1280: (e = tab[i]) != null; jtulach@1280: i = nextIndex(i, len)) { jtulach@1280: ThreadLocal k = e.get(); jtulach@1280: if (k == null) { jtulach@1280: e.value = null; jtulach@1280: tab[i] = null; jtulach@1280: size--; jtulach@1280: } else { jtulach@1280: int h = k.threadLocalHashCode & (len - 1); jtulach@1280: if (h != i) { jtulach@1280: tab[i] = null; jtulach@1280: jtulach@1280: // Unlike Knuth 6.4 Algorithm R, we must scan until jtulach@1280: // null because multiple entries could have been stale. jtulach@1280: while (tab[h] != null) jtulach@1280: h = nextIndex(h, len); jtulach@1280: tab[h] = e; jtulach@1280: } jtulach@1280: } jtulach@1280: } jtulach@1280: return i; jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Heuristically scan some cells looking for stale entries. jtulach@1280: * This is invoked when either a new element is added, or jtulach@1280: * another stale one has been expunged. It performs a jtulach@1280: * logarithmic number of scans, as a balance between no jtulach@1280: * scanning (fast but retains garbage) and a number of scans jtulach@1280: * proportional to number of elements, that would find all jtulach@1280: * garbage but would cause some insertions to take O(n) time. jtulach@1280: * jtulach@1280: * @param i a position known NOT to hold a stale entry. The jtulach@1280: * scan starts at the element after i. jtulach@1280: * jtulach@1280: * @param n scan control: log2(n) cells are scanned, jtulach@1280: * unless a stale entry is found, in which case jtulach@1280: * log2(table.length)-1 additional cells are scanned. jtulach@1280: * When called from insertions, this parameter is the number jtulach@1280: * of elements, but when from replaceStaleEntry, it is the jtulach@1280: * table length. (Note: all this could be changed to be either jtulach@1280: * more or less aggressive by weighting n instead of just jtulach@1280: * using straight log n. But this version is simple, fast, and jtulach@1280: * seems to work well.) jtulach@1280: * jtulach@1280: * @return true if any stale entries have been removed. jtulach@1280: */ jtulach@1280: private boolean cleanSomeSlots(int i, int n) { jtulach@1280: boolean removed = false; jtulach@1280: Entry[] tab = table; jtulach@1280: int len = tab.length; jtulach@1280: do { jtulach@1280: i = nextIndex(i, len); jtulach@1280: Entry e = tab[i]; jtulach@1280: if (e != null && e.get() == null) { jtulach@1280: n = len; jtulach@1280: removed = true; jtulach@1280: i = expungeStaleEntry(i); jtulach@1280: } jtulach@1280: } while ( (n >>>= 1) != 0); jtulach@1280: return removed; jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Re-pack and/or re-size the table. First scan the entire jtulach@1280: * table removing stale entries. If this doesn't sufficiently jtulach@1280: * shrink the size of the table, double the table size. jtulach@1280: */ jtulach@1280: private void rehash() { jtulach@1280: expungeStaleEntries(); jtulach@1280: jtulach@1280: // Use lower threshold for doubling to avoid hysteresis jtulach@1280: if (size >= threshold - threshold / 4) jtulach@1280: resize(); jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Double the capacity of the table. jtulach@1280: */ jtulach@1280: private void resize() { jtulach@1280: Entry[] oldTab = table; jtulach@1280: int oldLen = oldTab.length; jtulach@1280: int newLen = oldLen * 2; jtulach@1280: Entry[] newTab = new Entry[newLen]; jtulach@1280: int count = 0; jtulach@1280: jtulach@1280: for (int j = 0; j < oldLen; ++j) { jtulach@1280: Entry e = oldTab[j]; jtulach@1280: if (e != null) { jtulach@1280: ThreadLocal k = e.get(); jtulach@1280: if (k == null) { jtulach@1280: e.value = null; // Help the GC jtulach@1280: } else { jtulach@1280: int h = k.threadLocalHashCode & (newLen - 1); jtulach@1280: while (newTab[h] != null) jtulach@1280: h = nextIndex(h, newLen); jtulach@1280: newTab[h] = e; jtulach@1280: count++; jtulach@1280: } jtulach@1280: } jtulach@1280: } jtulach@1280: jtulach@1280: setThreshold(newLen); jtulach@1280: size = count; jtulach@1280: table = newTab; jtulach@1280: } jtulach@1280: jtulach@1280: /** jtulach@1280: * Expunge all stale entries in the table. jtulach@1280: */ jtulach@1280: private void expungeStaleEntries() { jtulach@1280: Entry[] tab = table; jtulach@1280: int len = tab.length; jtulach@1280: for (int j = 0; j < len; j++) { jtulach@1280: Entry e = tab[j]; jtulach@1280: if (e != null && e.get() == null) jtulach@1280: expungeStaleEntry(j); jtulach@1280: } jtulach@1280: } jtulach@1280: } jtulach@1280: }