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