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