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