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