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