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