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