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