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