1 /*
  2  * Copyright (c) 1997, 2020, 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 
 28 import java.lang.ref.WeakReference;
 29 import java.util.Objects;
 30 import java.util.concurrent.atomic.AtomicInteger;
 31 import java.util.function.Supplier;
 32 
 33 import jdk.internal.misc.TerminatingThreadLocal;
 34 
 35 /**
 36  * This class provides thread-local variables.  These variables differ from
 37  * their normal counterparts in that each thread that accesses one (via its
 38  * {@code get} or {@code set} method) has its own, independently initialized
 39  * copy of the variable.  {@code ThreadLocal} instances are typically private
 40  * static fields in classes that wish to associate state with a thread (e.g.,
 41  * a user ID or Transaction ID).
 42  *
 43  * <p>For example, the class below generates unique identifiers local to each
 44  * thread.
 45  * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
 46  * and remains unchanged on subsequent calls.
 47  * <pre>
 48  * import java.util.concurrent.atomic.AtomicInteger;
 49  *
 50  * public class ThreadId {
 51  *     // Atomic integer containing the next thread ID to be assigned
 52  *     private static final AtomicInteger nextId = new AtomicInteger(0);
 53  *
 54  *     // Thread local variable containing each thread's ID
 55  *     private static final ThreadLocal&lt;Integer&gt; threadId =
 56  *         new ThreadLocal&lt;Integer&gt;() {
 57  *             &#64;Override protected Integer initialValue() {
 58  *                 return nextId.getAndIncrement();
 59  *         }
 60  *     };
 61  *
 62  *     // Returns the current thread's unique ID, assigning it if necessary
 63  *     public static int get() {
 64  *         return threadId.get();
 65  *     }
 66  * }
 67  * </pre>
 68  * <p>Each thread holds an implicit reference to its copy of a thread-local
 69  * variable as long as the thread is alive and the {@code ThreadLocal}
 70  * instance is accessible; after a thread goes away, all of its copies of
 71  * thread-local instances are subject to garbage collection (unless other
 72  * references to these copies exist).
 73  *
 74  * @author  Josh Bloch and Doug Lea
 75  * @since   1.2
 76  */
 77 public class ThreadLocal<T> {
 78     /**
 79      * ThreadLocals rely on per-thread linear-probe hash maps attached
 80      * to each thread (Thread.threadLocals and
 81      * inheritableThreadLocals).  The ThreadLocal objects act as keys,
 82      * searched via threadLocalHashCode.  This is a custom hash code
 83      * (useful only within ThreadLocalMaps) that eliminates collisions
 84      * in the common case where consecutively constructed ThreadLocals
 85      * are used by the same threads, while remaining well-behaved in
 86      * less common cases.
 87      */
 88     private final int threadLocalHashCode = nextHashCode();
 89 
 90     /**
 91      * The next hash code to be given out. Updated atomically. Starts at
 92      * zero.
 93      */
 94     private static AtomicInteger nextHashCode =
 95         new AtomicInteger();
 96 
 97     /**
 98      * The difference between successively generated hash codes - turns
 99      * implicit sequential thread-local IDs into near-optimally spread
100      * multiplicative hash values for power-of-two-sized tables.
101      */
102     private static final int HASH_INCREMENT = 0x61c88647;
103 
104     /**
105      * Returns the next hash code.
106      */
107     static int nextHashCode() {
108         return nextHashCode.getAndAdd(HASH_INCREMENT);
109     }
110 
111     /**
112      * Returns the current thread's "initial value" for this
113      * thread-local variable.  This method will be invoked the first
114      * time a thread accesses the variable with the {@link #get}
115      * method, unless the thread previously invoked the {@link #set}
116      * method, in which case the {@code initialValue} method will not
117      * be invoked for the thread.  Normally, this method is invoked at
118      * most once per thread, but it may be invoked again in case of
119      * subsequent invocations of {@link #remove} followed by {@link #get}.
120      *
121      * <p>This implementation simply returns {@code null}; if the
122      * programmer desires thread-local variables to have an initial
123      * value other than {@code null}, {@code ThreadLocal} must be
124      * subclassed, and this method overridden.  Typically, an
125      * anonymous inner class will be used.
126      *
127      * @return the initial value for this thread-local
128      */
129     protected T initialValue() {
130         return null;
131     }
132 
133     /**
134      * Creates a thread local variable. The initial value of the variable is
135      * determined by invoking the {@code get} method on the {@code Supplier}.
136      *
137      * @param <S> the type of the thread local's value
138      * @param supplier the supplier to be used to determine the initial value
139      * @return a new thread local variable
140      * @throws NullPointerException if the specified supplier is null
141      * @since 1.8
142      */
143     public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
144         return new SuppliedThreadLocal<>(supplier);
145     }
146 
147     /**
148      * Creates a thread local variable.
149      * @see #withInitial(java.util.function.Supplier)
150      */
151     public ThreadLocal() {
152     }
153 
154     /**
155      * Returns the value in the current thread's copy of this
156      * thread-local variable.  If the variable has no value for the
157      * current thread, it is first initialized to the value returned
158      * by an invocation of the {@link #initialValue} method.
159      * If the current thread does not support thread locals then
160      * this method returns its {@link #initialValue} (or {@code null}
161      * if the {@code initialValue} method is not overridden).
162      *
163      * @return the current thread's value of this thread-local
164      * @see Thread.Builder#allowSetThreadLocals(boolean)
165      */
166     public T get() {
167         return get(Thread.currentThread());
168     }
169 
170     /**
171      * Returns the value in the current carrier thread's copy of this
172      * thread-local variable.
173      */
174     T getCarrierThreadLocal() {
175         return get(Thread.currentCarrierThread());
176     }
177 
178     private T get(Thread t) {
179         ThreadLocalMap map = getMap(t);
180         if (map != null && map != ThreadLocalMap.NOT_SUPPORTED) {
181             ThreadLocalMap.Entry e = map.getEntry(this);
182             if (e != null) {
183                 @SuppressWarnings("unchecked")
184                 T result = (T)e.value;
185                 return result;
186             }
187         }
188         return setInitialValue(t);
189     }
190 
191     /**
192      * Returns {@code true} if there is a value in the current thread's copy of
193      * this thread-local variable, even if that values is {@code null}.
194      *
195      * @return {@code true} if current thread has associated value in this
196      *         thread-local variable; {@code false} if not
197      */
198     boolean isPresent() {
199         Thread t = Thread.currentThread();
200         ThreadLocalMap map = getMap(t);
201         if (map != null && map != ThreadLocalMap.NOT_SUPPORTED) {
202             return map.getEntry(this) != null;
203         } else {
204             return false;
205         }
206     }
207 
208     /**
209      * Variant of set() to establish initialValue. Used instead
210      * of set() in case user has overridden the set() method.
211      *
212      * @return the initial value
213      */
214     private T setInitialValue(Thread t) {
215         T value = initialValue();

216         ThreadLocalMap map = getMap(t);
217         if (map == ThreadLocalMap.NOT_SUPPORTED) {
218             return value;
219         }
220         if (map != null) {
221             map.set(this, value);
222         } else {
223             createMap(t, value);
224         }
225         if (this instanceof TerminatingThreadLocal) {
226             TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
227         }
228         return value;
229     }
230 
231     /**
232      * Sets the current thread's copy of this thread-local variable
233      * to the specified value.  Most subclasses will have no need to
234      * override this method, relying solely on the {@link #initialValue}
235      * method to set the values of thread-locals.
236      *
237      * @param value the value to be stored in the current thread's copy of
238      *        this thread-local.
239      *
240      * @throws UnsupportedOperationException if the current thread is not
241      *         allowed to set its copy of thread-local variables
242      *
243      * @see Thread.Builder#allowSetThreadLocals(boolean)
244      */
245     public void set(T value) {
246         set(Thread.currentThread(), value);
247     }
248 
249     void setCarrierThreadLocal(T value) {
250         set(Thread.currentCarrierThread(), value);
251     }
252 
253     private void set(Thread t, T value) {
254         ThreadLocalMap map = getMap(t);
255         if (map == ThreadLocalMap.NOT_SUPPORTED) {
256             throw new UnsupportedOperationException();
257         }
258         if (map != null) {
259             map.set(this, value);
260         } else {
261             createMap(t, value);
262         }
263     }
264 
265     /**
266      * Removes the current thread's value for this thread-local
267      * variable.  If this thread-local variable is subsequently
268      * {@linkplain #get read} by the current thread, its value will be
269      * reinitialized by invoking its {@link #initialValue} method,
270      * unless its value is {@linkplain #set set} by the current thread
271      * in the interim.  This may result in multiple invocations of the
272      * {@code initialValue} method in the current thread.
273      *
274      * @since 1.5
275      */
276      public void remove() {
277          ThreadLocalMap m = getMap(Thread.currentThread());
278          if (m != null && m != ThreadLocalMap.NOT_SUPPORTED) {
279              m.remove(this);
280          }
281      }
282 
283     /**
284      * Get the map associated with a ThreadLocal. Overridden in
285      * InheritableThreadLocal.
286      *
287      * @param  t the current thread
288      * @return the map
289      */
290     ThreadLocalMap getMap(Thread t) {
291         return t.threadLocals;
292     }
293 
294     /**
295      * Create the map associated with a ThreadLocal. Overridden in
296      * InheritableThreadLocal.
297      *
298      * @param t the current thread
299      * @param firstValue value for the initial entry of the map
300      */
301     void createMap(Thread t, T firstValue) {
302         t.threadLocals = new ThreadLocalMap(this, firstValue);
303     }
304 
305     /**
306      * Factory method to create map of inherited thread locals.
307      * Designed to be called only from Thread constructor.
308      *
309      * @param  parentMap the map associated with parent thread
310      * @return a map containing the parent's inheritable bindings
311      */
312     static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
313         return new ThreadLocalMap(parentMap);
314     }
315 
316     /**
317      * Method childValue is visibly defined in subclass
318      * InheritableThreadLocal, but is internally defined here for the
319      * sake of providing createInheritedMap factory method without
320      * needing to subclass the map class in InheritableThreadLocal.
321      * This technique is preferable to the alternative of embedding
322      * instanceof tests in methods.
323      */
324     T childValue(T parentValue) {
325         throw new UnsupportedOperationException();
326     }
327 
328     /**
329      * An extension of ThreadLocal that obtains its initial value from
330      * the specified {@code Supplier}.
331      */
332     static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
333 
334         private final Supplier<? extends T> supplier;
335 
336         SuppliedThreadLocal(Supplier<? extends T> supplier) {
337             this.supplier = Objects.requireNonNull(supplier);
338         }
339 
340         @Override
341         protected T initialValue() {
342             return supplier.get();
343         }
344     }
345 
346     /**
347      * ThreadLocalMap is a customized hash map suitable only for
348      * maintaining thread local values. No operations are exported
349      * outside of the ThreadLocal class. The class is package private to
350      * allow declaration of fields in class Thread.  To help deal with
351      * very large and long-lived usages, the hash table entries use
352      * WeakReferences for keys. However, since reference queues are not
353      * used, stale entries are guaranteed to be removed only when
354      * the table starts running out of space.
355      */
356     static class ThreadLocalMap {
357 
358         /**
359          * The entries in this hash map extend WeakReference, using
360          * its main ref field as the key (which is always a
361          * ThreadLocal object).  Note that null keys (i.e. entry.get()
362          * == null) mean that the key is no longer referenced, so the
363          * entry can be expunged from table.  Such entries are referred to
364          * as "stale entries" in the code that follows.
365          */
366         static class Entry extends WeakReference<ThreadLocal<?>> {
367             /** The value associated with this ThreadLocal. */
368             Object value;
369 
370             Entry(ThreadLocal<?> k, Object v) {
371                 super(k);
372                 value = v;
373             }
374         }
375 
376         static final ThreadLocalMap NOT_SUPPORTED = new ThreadLocalMap();
377 
378         /**
379          * The initial capacity -- MUST be a power of two.
380          */
381         private static final int INITIAL_CAPACITY = 16;
382 
383         /**
384          * The table, resized as necessary.
385          * table.length MUST always be a power of two.
386          */
387         private Entry[] table;
388 
389         /**
390          * The number of entries in the table.
391          */
392         private int size = 0;
393 
394         /**
395          * The next size value at which to resize.
396          */
397         private int threshold; // Default to 0
398 
399         /**
400          * Set the resize threshold to maintain at worst a 2/3 load factor.
401          */
402         private void setThreshold(int len) {
403             threshold = len * 2 / 3;
404         }
405 
406         /**
407          * Increment i modulo len.
408          */
409         private static int nextIndex(int i, int len) {
410             return ((i + 1 < len) ? i + 1 : 0);
411         }
412 
413         /**
414          * Decrement i modulo len.
415          */
416         private static int prevIndex(int i, int len) {
417             return ((i - 1 >= 0) ? i - 1 : len - 1);
418         }
419 
420         ThreadLocalMap() {
421         }
422 
423         /**
424          * Construct a new map initially containing (firstKey, firstValue).
425          * ThreadLocalMaps are constructed lazily, so we only create
426          * one when we have at least one entry to put in it.
427          */
428         ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
429             table = new Entry[INITIAL_CAPACITY];
430             int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
431             table[i] = new Entry(firstKey, firstValue);
432             size = 1;
433             setThreshold(INITIAL_CAPACITY);
434         }
435 
436         /**
437          * Construct a new map including all Inheritable ThreadLocals
438          * from given parent map. Called only by createInheritedMap.
439          *
440          * @param parentMap the map associated with parent thread.
441          */
442         private ThreadLocalMap(ThreadLocalMap parentMap) {
443             Entry[] parentTable = parentMap.table;
444             int len = parentTable.length;
445             setThreshold(len);
446             table = new Entry[len];
447 
448             for (Entry e : parentTable) {
449                 if (e != null) {
450                     @SuppressWarnings("unchecked")
451                     ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
452                     if (key != null) {
453                         Object value = key.childValue(e.value);
454                         Entry c = new Entry(key, value);
455                         int h = key.threadLocalHashCode & (len - 1);
456                         while (table[h] != null)
457                             h = nextIndex(h, len);
458                         table[h] = c;
459                         size++;
460                     }
461                 }
462             }
463         }
464 
465         /**
466          * Returns the number of elements in the map.
467          */
468         int size() {
469             return size;
470         }
471 
472         /**
473          * Get the entry associated with key.  This method
474          * itself handles only the fast path: a direct hit of existing
475          * key. It otherwise relays to getEntryAfterMiss.  This is
476          * designed to maximize performance for direct hits, in part
477          * by making this method readily inlinable.
478          *
479          * @param  key the thread local object
480          * @return the entry associated with key, or null if no such
481          */
482         private Entry getEntry(ThreadLocal<?> key) {
483             int i = key.threadLocalHashCode & (table.length - 1);
484             Entry e = table[i];
485             if (e != null && e.refersTo(key))
486                 return e;
487             else
488                 return getEntryAfterMiss(key, i, e);
489         }
490 
491         /**
492          * Version of getEntry method for use when key is not found in
493          * its direct hash slot.
494          *
495          * @param  key the thread local object
496          * @param  i the table index for key's hash code
497          * @param  e the entry at table[i]
498          * @return the entry associated with key, or null if no such
499          */
500         private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
501             Entry[] tab = table;
502             int len = tab.length;
503 
504             while (e != null) {
505                 if (e.refersTo(key))
506                     return e;
507                 if (e.refersTo(null))
508                     expungeStaleEntry(i);
509                 else
510                     i = nextIndex(i, len);
511                 e = tab[i];
512             }
513             return null;
514         }
515 
516         /**
517          * Set the value associated with key.
518          *
519          * @param key the thread local object
520          * @param value the value to be set
521          */
522         private void set(ThreadLocal<?> key, Object value) {
523 
524             // We don't use a fast path as with get() because it is at
525             // least as common to use set() to create new entries as
526             // it is to replace existing ones, in which case, a fast
527             // path would fail more often than not.
528 
529             Entry[] tab = table;
530             int len = tab.length;
531             int i = key.threadLocalHashCode & (len-1);
532 
533             for (Entry e = tab[i];
534                  e != null;
535                  e = tab[i = nextIndex(i, len)]) {
536                 if (e.refersTo(key)) {
537                     e.value = value;
538                     return;
539                 }
540 
541                 if (e.refersTo(null)) {
542                     replaceStaleEntry(key, value, i);
543                     return;
544                 }
545             }
546 
547             tab[i] = new Entry(key, value);
548             int sz = ++size;
549             if (!cleanSomeSlots(i, sz) && sz >= threshold)
550                 rehash();
551         }
552 
553         /**
554          * Remove the entry for key.
555          */
556         private void remove(ThreadLocal<?> key) {
557             Entry[] tab = table;
558             int len = tab.length;
559             int i = key.threadLocalHashCode & (len-1);
560             for (Entry e = tab[i];
561                  e != null;
562                  e = tab[i = nextIndex(i, len)]) {
563                 if (e.refersTo(key)) {
564                     e.clear();
565                     expungeStaleEntry(i);
566                     return;
567                 }
568             }
569         }
570 
571         /**
572          * Replace a stale entry encountered during a set operation
573          * with an entry for the specified key.  The value passed in
574          * the value parameter is stored in the entry, whether or not
575          * an entry already exists for the specified key.
576          *
577          * As a side effect, this method expunges all stale entries in the
578          * "run" containing the stale entry.  (A run is a sequence of entries
579          * between two null slots.)
580          *
581          * @param  key the key
582          * @param  value the value to be associated with key
583          * @param  staleSlot index of the first stale entry encountered while
584          *         searching for key.
585          */
586         private void replaceStaleEntry(ThreadLocal<?> key, Object value,
587                                        int staleSlot) {
588             Entry[] tab = table;
589             int len = tab.length;
590             Entry e;
591 
592             // Back up to check for prior stale entry in current run.
593             // We clean out whole runs at a time to avoid continual
594             // incremental rehashing due to garbage collector freeing
595             // up refs in bunches (i.e., whenever the collector runs).
596             int slotToExpunge = staleSlot;
597             for (int i = prevIndex(staleSlot, len);
598                  (e = tab[i]) != null;
599                  i = prevIndex(i, len))
600                 if (e.refersTo(null))
601                     slotToExpunge = i;
602 
603             // Find either the key or trailing null slot of run, whichever
604             // occurs first
605             for (int i = nextIndex(staleSlot, len);
606                  (e = tab[i]) != null;
607                  i = nextIndex(i, len)) {
608                 // If we find key, then we need to swap it
609                 // with the stale entry to maintain hash table order.
610                 // The newly stale slot, or any other stale slot
611                 // encountered above it, can then be sent to expungeStaleEntry
612                 // to remove or rehash all of the other entries in run.
613                 if (e.refersTo(key)) {
614                     e.value = value;
615 
616                     tab[i] = tab[staleSlot];
617                     tab[staleSlot] = e;
618 
619                     // Start expunge at preceding stale entry if it exists
620                     if (slotToExpunge == staleSlot)
621                         slotToExpunge = i;
622                     cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
623                     return;
624                 }
625 
626                 // If we didn't find stale entry on backward scan, the
627                 // first stale entry seen while scanning for key is the
628                 // first still present in the run.
629                 if (e.refersTo(null) && slotToExpunge == staleSlot)
630                     slotToExpunge = i;
631             }
632 
633             // If key not found, put new entry in stale slot
634             tab[staleSlot].value = null;
635             tab[staleSlot] = new Entry(key, value);
636 
637             // If there are any other stale entries in run, expunge them
638             if (slotToExpunge != staleSlot)
639                 cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
640         }
641 
642         /**
643          * Expunge a stale entry by rehashing any possibly colliding entries
644          * lying between staleSlot and the next null slot.  This also expunges
645          * any other stale entries encountered before the trailing null.  See
646          * Knuth, Section 6.4
647          *
648          * @param staleSlot index of slot known to have null key
649          * @return the index of the next null slot after staleSlot
650          * (all between staleSlot and this slot will have been checked
651          * for expunging).
652          */
653         private int expungeStaleEntry(int staleSlot) {
654             Entry[] tab = table;
655             int len = tab.length;
656 
657             // expunge entry at staleSlot
658             tab[staleSlot].value = null;
659             tab[staleSlot] = null;
660             size--;
661 
662             // Rehash until we encounter null
663             Entry e;
664             int i;
665             for (i = nextIndex(staleSlot, len);
666                  (e = tab[i]) != null;
667                  i = nextIndex(i, len)) {
668                 ThreadLocal<?> k = e.get();
669                 if (k == null) {
670                     e.value = null;
671                     tab[i] = null;
672                     size--;
673                 } else {
674                     int h = k.threadLocalHashCode & (len - 1);
675                     if (h != i) {
676                         tab[i] = null;
677 
678                         // Unlike Knuth 6.4 Algorithm R, we must scan until
679                         // null because multiple entries could have been stale.
680                         while (tab[h] != null)
681                             h = nextIndex(h, len);
682                         tab[h] = e;
683                     }
684                 }
685             }
686             return i;
687         }
688 
689         /**
690          * Heuristically scan some cells looking for stale entries.
691          * This is invoked when either a new element is added, or
692          * another stale one has been expunged. It performs a
693          * logarithmic number of scans, as a balance between no
694          * scanning (fast but retains garbage) and a number of scans
695          * proportional to number of elements, that would find all
696          * garbage but would cause some insertions to take O(n) time.
697          *
698          * @param i a position known NOT to hold a stale entry. The
699          * scan starts at the element after i.
700          *
701          * @param n scan control: {@code log2(n)} cells are scanned,
702          * unless a stale entry is found, in which case
703          * {@code log2(table.length)-1} additional cells are scanned.
704          * When called from insertions, this parameter is the number
705          * of elements, but when from replaceStaleEntry, it is the
706          * table length. (Note: all this could be changed to be either
707          * more or less aggressive by weighting n instead of just
708          * using straight log n. But this version is simple, fast, and
709          * seems to work well.)
710          *
711          * @return true if any stale entries have been removed.
712          */
713         private boolean cleanSomeSlots(int i, int n) {
714             boolean removed = false;
715             Entry[] tab = table;
716             int len = tab.length;
717             do {
718                 i = nextIndex(i, len);
719                 Entry e = tab[i];
720                 if (e != null && e.refersTo(null)) {
721                     n = len;
722                     removed = true;
723                     i = expungeStaleEntry(i);
724                 }
725             } while ( (n >>>= 1) != 0);
726             return removed;
727         }
728 
729         /**
730          * Re-pack and/or re-size the table. First scan the entire
731          * table removing stale entries. If this doesn't sufficiently
732          * shrink the size of the table, double the table size.
733          */
734         private void rehash() {
735             expungeStaleEntries();
736 
737             // Use lower threshold for doubling to avoid hysteresis
738             if (size >= threshold - threshold / 4)
739                 resize();
740         }
741 
742         /**
743          * Double the capacity of the table.
744          */
745         private void resize() {
746             Entry[] oldTab = table;
747             int oldLen = oldTab.length;
748             int newLen = oldLen * 2;
749             Entry[] newTab = new Entry[newLen];
750             int count = 0;
751 
752             for (Entry e : oldTab) {
753                 if (e != null) {
754                     ThreadLocal<?> k = e.get();
755                     if (k == null) {
756                         e.value = null; // Help the GC
757                     } else {
758                         int h = k.threadLocalHashCode & (newLen - 1);
759                         while (newTab[h] != null)
760                             h = nextIndex(h, newLen);
761                         newTab[h] = e;
762                         count++;
763                     }
764                 }
765             }
766 
767             setThreshold(newLen);
768             size = count;
769             table = newTab;
770         }
771 
772         /**
773          * Expunge all stale entries in the table.
774          */
775         private void expungeStaleEntries() {
776             Entry[] tab = table;
777             int len = tab.length;
778             for (int j = 0; j < len; j++) {
779                 Entry e = tab[j];
780                 if (e != null && e.refersTo(null))
781                     expungeStaleEntry(j);
782             }
783         }
784     }
785 }
--- EOF ---