1 /* 2 * Copyright (c) 1994, 2025, 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.Reference; 29 import java.lang.reflect.Field; 30 import java.time.Duration; 31 import java.util.Map; 32 import java.util.HashMap; 33 import java.util.Objects; 34 import java.util.concurrent.ThreadFactory; 35 import java.util.concurrent.StructureViolationException; 36 import java.util.concurrent.locks.LockSupport; 37 import jdk.internal.event.ThreadSleepEvent; 38 import jdk.internal.misc.TerminatingThreadLocal; 39 import jdk.internal.misc.Unsafe; 40 import jdk.internal.misc.VM; 41 import jdk.internal.vm.Continuation; 42 import jdk.internal.vm.ScopedValueContainer; 43 import jdk.internal.vm.StackableScope; 44 import jdk.internal.vm.ThreadContainer; 45 import jdk.internal.vm.annotation.ForceInline; 46 import jdk.internal.vm.annotation.Hidden; 47 import jdk.internal.vm.annotation.IntrinsicCandidate; 48 import jdk.internal.vm.annotation.Stable; 49 import sun.nio.ch.Interruptible; 50 import static java.util.concurrent.TimeUnit.MILLISECONDS; 51 import static java.util.concurrent.TimeUnit.NANOSECONDS; 52 53 /** 54 * A <i>thread</i> is a thread of execution in a program. The Java 55 * virtual machine allows an application to have multiple threads of 56 * execution running concurrently. 57 * 58 * <p> {@code Thread} defines constructors and a {@link Builder} to create threads. 59 * {@linkplain #start() Starting} a thread schedules it to execute its {@link #run() run} 60 * method. The newly started thread executes concurrently with the thread that caused 61 * it to start. 62 * 63 * <p> A thread <i>terminates</i> if either its {@code run} method completes normally, 64 * or if its {@code run} method completes abruptly and the appropriate {@linkplain 65 * Thread.UncaughtExceptionHandler uncaught exception handler} completes normally or 66 * abruptly. With no code left to run, the thread has completed execution. The 67 * {@link #join() join} method can be used to wait for a thread to terminate. 68 * 69 * <p> Threads have a unique {@linkplain #threadId() identifier} and a {@linkplain 70 * #getName() name}. The identifier is generated when a {@code Thread} is created 71 * and cannot be changed. The thread name can be specified when creating a thread 72 * or can be {@linkplain #setName(String) changed} at a later time. 73 * 74 * <p> Threads support {@link ThreadLocal} variables. These are variables that are 75 * local to a thread, meaning a thread can have a copy of a variable that is set to 76 * a value that is independent of the value set by other threads. {@code Thread} also 77 * supports {@link InheritableThreadLocal} variables that are thread local variables 78 * that are inherited at thread creation time from the parent {@code Thread}. 79 * {@code Thread} supports a special inheritable thread local for the thread 80 * {@linkplain #getContextClassLoader() context-class-loader}. 81 * 82 * <h2><a id="platform-threads">Platform threads</a></h2> 83 * <p> {@code Thread} supports the creation of <i>platform threads</i> that are 84 * typically mapped 1:1 to kernel threads scheduled by the operating system. 85 * Platform threads will usually have a large stack and other resources that are 86 * maintained by the operating system. Platforms threads are suitable for executing 87 * all types of tasks but may be a limited resource. 88 * 89 * <p> Platform threads get an automatically generated thread name by default. 90 * 91 * <p> Platform threads are designated <i>daemon</i> or <i>non-daemon</i> threads. 92 * When the Java virtual machine starts up, there is usually one non-daemon 93 * thread (the thread that typically calls the application's {@code main} method). 94 * The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all started 95 * non-daemon threads have terminated. Unstarted non-daemon threads do not prevent 96 * the shutdown sequence from beginning. 97 * 98 * <p> In addition to the daemon status, platform threads have a {@linkplain 99 * #getPriority() thread priority} and are members of a {@linkplain ThreadGroup 100 * thread group}. 101 * 102 * <h2><a id="virtual-threads">Virtual threads</a></h2> 103 * <p> {@code Thread} also supports the creation of <i>virtual threads</i>. 104 * Virtual threads are typically <i>user-mode threads</i> scheduled by the Java 105 * runtime rather than the operating system. Virtual threads will typically require 106 * few resources and a single Java virtual machine may support millions of virtual 107 * threads. Virtual threads are suitable for executing tasks that spend most of 108 * the time blocked, often waiting for I/O operations to complete. Virtual threads 109 * are not intended for long running CPU intensive operations. 110 * 111 * <p> Virtual threads typically employ a small set of platform threads used as 112 * <em>carrier threads</em>. Locking and I/O operations are examples of operations 113 * where a carrier thread may be re-scheduled from one virtual thread to another. 114 * Code executing in a virtual thread is not aware of the underlying carrier thread. 115 * The {@linkplain Thread#currentThread()} method, used to obtain a reference 116 * to the <i>current thread</i>, will always return the {@code Thread} object 117 * for the virtual thread. 118 * 119 * <p> Virtual threads do not have a thread name by default. The {@link #getName() 120 * getName} method returns the empty string if a thread name is not set. 121 * 122 * <p> Virtual threads are daemon threads and so do not prevent the 123 * <a href="Runtime.html#shutdown">shutdown sequence</a> from beginning. 124 * Virtual threads have a fixed {@linkplain #getPriority() thread priority} 125 * that cannot be changed. 126 * 127 * <h2>Creating and starting threads</h2> 128 * 129 * <p> {@code Thread} defines public constructors for creating platform threads and 130 * the {@link #start() start} method to schedule threads to execute. {@code Thread} 131 * may be extended for customization and other advanced reasons although most 132 * applications should have little need to do this. 133 * 134 * <p> {@code Thread} defines a {@link Builder} API for creating and starting both 135 * platform and virtual threads. The following are examples that use the builder: 136 * {@snippet : 137 * Runnable runnable = ... 138 * 139 * // Start a daemon thread to run a task 140 * Thread thread = Thread.ofPlatform().daemon().start(runnable); 141 * 142 * // Create an unstarted thread with name "duke", its start() method 143 * // must be invoked to schedule it to execute. 144 * Thread thread = Thread.ofPlatform().name("duke").unstarted(runnable); 145 * 146 * // A ThreadFactory that creates daemon threads named "worker-0", "worker-1", ... 147 * ThreadFactory factory = Thread.ofPlatform().daemon().name("worker-", 0).factory(); 148 * 149 * // Start a virtual thread to run a task 150 * Thread thread = Thread.ofVirtual().start(runnable); 151 * 152 * // A ThreadFactory that creates virtual threads 153 * ThreadFactory factory = Thread.ofVirtual().factory(); 154 * } 155 * 156 * <h2><a id="inheritance">Inheritance when creating threads</a></h2> 157 * A {@code Thread} created with one of the public constructors inherits the daemon 158 * status and thread priority from the parent thread at the time that the child {@code 159 * Thread} is created. The {@linkplain ThreadGroup thread group} is also inherited when 160 * not provided to the constructor. When using a {@code Thread.Builder} to create a 161 * platform thread, the daemon status, thread priority, and thread group are inherited 162 * when not set on the builder. As with the constructors, inheriting from the parent 163 * thread is done when the child {@code Thread} is created. 164 * 165 * <p> A {@code Thread} inherits its initial values of {@linkplain InheritableThreadLocal 166 * inheritable-thread-local} variables (including the context class loader) from 167 * the parent thread values at the time that the child {@code Thread} is created. 168 * The 5-param {@linkplain Thread#Thread(ThreadGroup, Runnable, String, long, boolean) 169 * constructor} can be used to create a thread that does not inherit its initial 170 * values from the constructing thread. When using a {@code Thread.Builder}, the 171 * {@link Builder#inheritInheritableThreadLocals(boolean) inheritInheritableThreadLocals} 172 * method can be used to select if the initial values are inherited. 173 * 174 * <p> Unless otherwise specified, passing a {@code null} argument to a constructor 175 * or method in this class will cause a {@link NullPointerException} to be thrown. 176 * 177 * @implNote 178 * In the JDK Reference Implementation, the virtual thread scheduler may be configured 179 * with the following system properties: 180 * <table class="striped"> 181 * <caption style="display:none">System properties</caption> 182 * <thead> 183 * <tr> 184 * <th scope="col">System property</th> 185 * <th scope="col">Description</th> 186 * </tr> 187 * </thead> 188 * <tbody> 189 * <tr> 190 * <th scope="row"> 191 * {@systemProperty jdk.virtualThreadScheduler.parallelism} 192 * </th> 193 * <td> The number of platform threads available for scheduling virtual 194 * threads. It defaults to the number of available processors. </td> 195 * </tr> 196 * <tr> 197 * <th scope="row"> 198 * {@systemProperty jdk.virtualThreadScheduler.maxPoolSize} 199 * </th> 200 * <td> The maximum number of platform threads available to the scheduler. 201 * It defaults to 256. </td> 202 * </tr> 203 * </tbody> 204 * </table> 205 * 206 * @since 1.0 207 */ 208 public class Thread implements Runnable { 209 /* Make sure registerNatives is the first thing <clinit> does. */ 210 private static native void registerNatives(); 211 static { 212 registerNatives(); 213 } 214 215 /* 216 * Reserved for exclusive use by the JVM. Cannot be moved to the FieldHolder 217 * as it needs to be set by the VM for JNI attaching threads, before executing 218 * the constructor that will create the FieldHolder. The historically named 219 * `eetop` holds the address of the underlying VM JavaThread, and is set to 220 * non-zero when the thread is started, and reset to zero when the thread terminates. 221 * A non-zero value indicates this thread isAlive(). 222 */ 223 private volatile long eetop; 224 225 // thread id 226 private final long tid; 227 228 // thread name 229 private volatile String name; 230 231 // interrupt status (read/written by VM) 232 volatile boolean interrupted; 233 234 // context ClassLoader 235 private volatile ClassLoader contextClassLoader; 236 237 // Additional fields for platform threads. 238 // All fields, except task and terminatingThreadLocals, are accessed directly by the VM. 239 private static class FieldHolder { 240 final ThreadGroup group; 241 final Runnable task; 242 final long stackSize; 243 volatile int priority; 244 volatile boolean daemon; 245 volatile int threadStatus; 246 247 // This map is maintained by the ThreadLocal class 248 ThreadLocal.ThreadLocalMap terminatingThreadLocals; 249 250 FieldHolder(ThreadGroup group, 251 Runnable task, 252 long stackSize, 253 int priority, 254 boolean daemon) { 255 this.group = group; 256 this.task = task; 257 this.stackSize = stackSize; 258 this.priority = priority; 259 if (daemon) 260 this.daemon = true; 261 } 262 } 263 private final FieldHolder holder; 264 265 ThreadLocal.ThreadLocalMap terminatingThreadLocals() { 266 return holder.terminatingThreadLocals; 267 } 268 269 void setTerminatingThreadLocals(ThreadLocal.ThreadLocalMap map) { 270 holder.terminatingThreadLocals = map; 271 } 272 273 /* 274 * ThreadLocal values pertaining to this thread. This map is maintained 275 * by the ThreadLocal class. 276 */ 277 private ThreadLocal.ThreadLocalMap threadLocals; 278 279 ThreadLocal.ThreadLocalMap threadLocals() { 280 return threadLocals; 281 } 282 283 void setThreadLocals(ThreadLocal.ThreadLocalMap map) { 284 threadLocals = map; 285 } 286 287 /* 288 * InheritableThreadLocal values pertaining to this thread. This map is 289 * maintained by the InheritableThreadLocal class. 290 */ 291 private ThreadLocal.ThreadLocalMap inheritableThreadLocals; 292 293 ThreadLocal.ThreadLocalMap inheritableThreadLocals() { 294 return inheritableThreadLocals; 295 } 296 297 void setInheritableThreadLocals(ThreadLocal.ThreadLocalMap map) { 298 inheritableThreadLocals = map; 299 } 300 301 /* 302 * Scoped value bindings are maintained by the ScopedValue class. 303 */ 304 private Object scopedValueBindings; 305 306 // Special value to indicate this is a newly-created Thread 307 // Note that his must match the declaration in ScopedValue. 308 private static final Object NEW_THREAD_BINDINGS = Thread.class; 309 310 static Object scopedValueBindings() { 311 return currentThread().scopedValueBindings; 312 } 313 314 static void setScopedValueBindings(Object bindings) { 315 currentThread().scopedValueBindings = bindings; 316 } 317 318 /** 319 * Search the stack for the most recent scoped-value bindings. 320 */ 321 @IntrinsicCandidate 322 static native Object findScopedValueBindings(); 323 324 /** 325 * Inherit the scoped-value bindings from the given container. 326 * Invoked when starting a thread. 327 */ 328 void inheritScopedValueBindings(ThreadContainer container) { 329 ScopedValueContainer.BindingsSnapshot snapshot; 330 if (container.owner() != null 331 && (snapshot = container.scopedValueBindings()) != null) { 332 333 // bindings established for running/calling an operation 334 Object bindings = snapshot.scopedValueBindings(); 335 if (currentThread().scopedValueBindings != bindings) { 336 throw new StructureViolationException("Scoped value bindings have changed"); 337 } 338 339 this.scopedValueBindings = bindings; 340 } 341 } 342 343 /* 344 * Lock object for thread interrupt. 345 */ 346 final Object interruptLock = new Object(); 347 348 /** 349 * The argument supplied to the current call to 350 * java.util.concurrent.locks.LockSupport.park. 351 * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker 352 * Accessed using java.util.concurrent.locks.LockSupport.getBlocker 353 */ 354 private volatile Object parkBlocker; 355 356 /* The object in which this thread is blocked in an interruptible I/O 357 * operation, if any. The blocker's interrupt method should be invoked 358 * after setting this thread's interrupt status. 359 */ 360 private Interruptible nioBlocker; 361 362 Interruptible nioBlocker() { 363 //assert Thread.holdsLock(interruptLock); 364 return nioBlocker; 365 } 366 367 /* Set the blocker field; invoked via jdk.internal.access.SharedSecrets 368 * from java.nio code 369 */ 370 void blockedOn(Interruptible b) { 371 //assert Thread.currentThread() == this; 372 synchronized (interruptLock) { 373 nioBlocker = b; 374 } 375 } 376 377 /** 378 * The minimum priority that a thread can have. 379 */ 380 public static final int MIN_PRIORITY = 1; 381 382 /** 383 * The default priority that is assigned to a thread. 384 */ 385 public static final int NORM_PRIORITY = 5; 386 387 /** 388 * The maximum priority that a thread can have. 389 */ 390 public static final int MAX_PRIORITY = 10; 391 392 /* 393 * Current inner-most continuation. 394 */ 395 private Continuation cont; 396 397 /** 398 * Returns the current continuation. 399 */ 400 Continuation getContinuation() { 401 return cont; 402 } 403 404 /** 405 * Sets the current continuation. 406 */ 407 void setContinuation(Continuation cont) { 408 this.cont = cont; 409 } 410 411 /** 412 * Returns the Thread object for the current platform thread. If the 413 * current thread is a virtual thread then this method returns the carrier. 414 */ 415 @IntrinsicCandidate 416 static native Thread currentCarrierThread(); 417 418 /** 419 * Returns the Thread object for the current thread. 420 * @return the current thread 421 */ 422 @IntrinsicCandidate 423 public static native Thread currentThread(); 424 425 /** 426 * Sets the Thread object to be returned by Thread.currentThread(). 427 */ 428 @IntrinsicCandidate 429 native void setCurrentThread(Thread thread); 430 431 // ScopedValue support: 432 433 @IntrinsicCandidate 434 static native Object[] scopedValueCache(); 435 436 @IntrinsicCandidate 437 static native void setScopedValueCache(Object[] cache); 438 439 @IntrinsicCandidate 440 static native void ensureMaterializedForStackWalk(Object o); 441 442 /** 443 * A hint to the scheduler that the current thread is willing to yield 444 * its current use of a processor. The scheduler is free to ignore this 445 * hint. 446 * 447 * <p> Yield is a heuristic attempt to improve relative progression 448 * between threads that would otherwise over-utilise a CPU. Its use 449 * should be combined with detailed profiling and benchmarking to 450 * ensure that it actually has the desired effect. 451 * 452 * <p> It is rarely appropriate to use this method. It may be useful 453 * for debugging or testing purposes, where it may help to reproduce 454 * bugs due to race conditions. It may also be useful when designing 455 * concurrency control constructs such as the ones in the 456 * {@link java.util.concurrent.locks} package. 457 */ 458 public static void yield() { 459 if (currentThread() instanceof VirtualThread vthread) { 460 vthread.tryYield(); 461 } else { 462 yield0(); 463 } 464 } 465 466 private static native void yield0(); 467 468 /** 469 * Called before sleeping to create a jdk.ThreadSleep event. 470 */ 471 private static ThreadSleepEvent beforeSleep(long nanos) { 472 try { 473 ThreadSleepEvent event = new ThreadSleepEvent(); 474 if (event.isEnabled()) { 475 event.time = nanos; 476 event.begin(); 477 return event; 478 } 479 } catch (OutOfMemoryError e) { 480 // ignore 481 } 482 return null; 483 } 484 485 486 /** 487 * Called after sleeping to commit the jdk.ThreadSleep event. 488 */ 489 private static void afterSleep(ThreadSleepEvent event) { 490 if (event != null) { 491 try { 492 event.commit(); 493 } catch (OutOfMemoryError e) { 494 // ignore 495 } 496 } 497 } 498 499 /** 500 * Sleep for the specified number of nanoseconds, subject to the precision 501 * and accuracy of system timers and schedulers. 502 */ 503 private static void sleepNanos(long nanos) throws InterruptedException { 504 ThreadSleepEvent event = beforeSleep(nanos); 505 try { 506 if (currentThread() instanceof VirtualThread vthread) { 507 vthread.sleepNanos(nanos); 508 } else { 509 sleepNanos0(nanos); 510 } 511 } finally { 512 afterSleep(event); 513 } 514 } 515 516 private static native void sleepNanos0(long nanos) throws InterruptedException; 517 518 /** 519 * Causes the currently executing thread to sleep (temporarily cease 520 * execution) for the specified number of milliseconds, subject to 521 * the precision and accuracy of system timers and schedulers. The thread 522 * does not lose ownership of any monitors. 523 * 524 * @param millis 525 * the length of time to sleep in milliseconds 526 * 527 * @throws IllegalArgumentException 528 * if the value of {@code millis} is negative 529 * 530 * @throws InterruptedException 531 * if any thread has interrupted the current thread. The 532 * <i>interrupted status</i> of the current thread is 533 * cleared when this exception is thrown. 534 */ 535 public static void sleep(long millis) throws InterruptedException { 536 if (millis < 0) { 537 throw new IllegalArgumentException("timeout value is negative"); 538 } 539 long nanos = MILLISECONDS.toNanos(millis); 540 sleepNanos(nanos); 541 } 542 543 /** 544 * Causes the currently executing thread to sleep (temporarily cease 545 * execution) for the specified number of milliseconds plus the specified 546 * number of nanoseconds, subject to the precision and accuracy of system 547 * timers and schedulers. The thread does not lose ownership of any 548 * monitors. 549 * 550 * @param millis 551 * the length of time to sleep in milliseconds 552 * 553 * @param nanos 554 * {@code 0-999999} additional nanoseconds to sleep 555 * 556 * @throws IllegalArgumentException 557 * if the value of {@code millis} is negative, or the value of 558 * {@code nanos} is not in the range {@code 0-999999} 559 * 560 * @throws InterruptedException 561 * if any thread has interrupted the current thread. The 562 * <i>interrupted status</i> of the current thread is 563 * cleared when this exception is thrown. 564 */ 565 public static void sleep(long millis, int nanos) throws InterruptedException { 566 if (millis < 0) { 567 throw new IllegalArgumentException("timeout value is negative"); 568 } 569 570 if (nanos < 0 || nanos > 999999) { 571 throw new IllegalArgumentException("nanosecond timeout value out of range"); 572 } 573 574 // total sleep time, in nanoseconds 575 long totalNanos = MILLISECONDS.toNanos(millis); 576 totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos); 577 sleepNanos(totalNanos); 578 } 579 580 /** 581 * Causes the currently executing thread to sleep (temporarily cease 582 * execution) for the specified duration, subject to the precision and 583 * accuracy of system timers and schedulers. This method is a no-op if 584 * the duration is {@linkplain Duration#isNegative() negative}. 585 * 586 * @param duration 587 * the duration to sleep 588 * 589 * @throws InterruptedException 590 * if the current thread is interrupted while sleeping. The 591 * <i>interrupted status</i> of the current thread is 592 * cleared when this exception is thrown. 593 * 594 * @since 19 595 */ 596 public static void sleep(Duration duration) throws InterruptedException { 597 long nanos = NANOSECONDS.convert(duration); // MAX_VALUE if > 292 years 598 if (nanos < 0) { 599 return; 600 } 601 sleepNanos(nanos); 602 } 603 604 /** 605 * Indicates that the caller is momentarily unable to progress, until the 606 * occurrence of one or more actions on the part of other activities. By 607 * invoking this method within each iteration of a spin-wait loop construct, 608 * the calling thread indicates to the runtime that it is busy-waiting. 609 * The runtime may take action to improve the performance of invoking 610 * spin-wait loop constructions. 611 * 612 * @apiNote 613 * As an example consider a method in a class that spins in a loop until 614 * some flag is set outside of that method. A call to the {@code onSpinWait} 615 * method should be placed inside the spin loop. 616 * {@snippet : 617 * class EventHandler { 618 * volatile boolean eventNotificationNotReceived; 619 * void waitForEventAndHandleIt() { 620 * while ( eventNotificationNotReceived ) { 621 * Thread.onSpinWait(); 622 * } 623 * readAndProcessEvent(); 624 * } 625 * 626 * void readAndProcessEvent() { 627 * // Read event from some source and process it 628 * . . . 629 * } 630 * } 631 * } 632 * <p> 633 * The code above would remain correct even if the {@code onSpinWait} 634 * method was not called at all. However on some architectures the Java 635 * Virtual Machine may issue the processor instructions to address such 636 * code patterns in a more beneficial way. 637 * 638 * @since 9 639 */ 640 @IntrinsicCandidate 641 public static void onSpinWait() {} 642 643 /** 644 * Characteristic value signifying that initial values for {@link 645 * InheritableThreadLocal inheritable-thread-locals} are not inherited from 646 * the constructing thread. 647 * See Thread initialization. 648 */ 649 static final int NO_INHERIT_THREAD_LOCALS = 1 << 2; 650 651 /** 652 * Thread identifier assigned to the primordial thread. 653 */ 654 static final long PRIMORDIAL_TID = 3; 655 656 /** 657 * Helper class to generate thread identifiers. The identifiers start at 658 * {@link Thread#PRIMORDIAL_TID} +1 as this class cannot be used during 659 * early startup to generate the identifier for the primordial thread. The 660 * counter is off-heap and shared with the VM to allow it to assign thread 661 * identifiers to non-Java threads. 662 * See Thread initialization. 663 */ 664 private static class ThreadIdentifiers { 665 private static final Unsafe U; 666 private static final long NEXT_TID_OFFSET; 667 static { 668 U = Unsafe.getUnsafe(); 669 NEXT_TID_OFFSET = Thread.getNextThreadIdOffset(); 670 } 671 static long next() { 672 return U.getAndAddLong(null, NEXT_TID_OFFSET, 1); 673 } 674 } 675 676 /** 677 * Initializes a platform Thread. 678 * 679 * @param g the Thread group, can be null 680 * @param name the name of the new Thread 681 * @param characteristics thread characteristics 682 * @param task the object whose run() method gets called 683 * @param stackSize the desired stack size for the new thread, or 684 * zero to indicate that this parameter is to be ignored. 685 */ 686 Thread(ThreadGroup g, String name, int characteristics, Runnable task, long stackSize) { 687 688 Thread parent = currentThread(); 689 boolean attached = (parent == this); // primordial or JNI attached 690 691 if (attached) { 692 if (g == null) { 693 throw new InternalError("group cannot be null when attaching"); 694 } 695 this.holder = new FieldHolder(g, task, stackSize, NORM_PRIORITY, false); 696 } else { 697 if (g == null) { 698 // default to current thread's group 699 g = parent.getThreadGroup(); 700 } 701 int priority = Math.min(parent.getPriority(), g.getMaxPriority()); 702 this.holder = new FieldHolder(g, task, stackSize, priority, parent.isDaemon()); 703 } 704 705 if (attached && VM.initLevel() < 1) { 706 this.tid = PRIMORDIAL_TID; // primordial thread 707 } else { 708 this.tid = ThreadIdentifiers.next(); 709 } 710 711 this.name = (name != null) ? name : genThreadName(); 712 713 // thread locals 714 if (!attached) { 715 if ((characteristics & NO_INHERIT_THREAD_LOCALS) == 0) { 716 ThreadLocal.ThreadLocalMap parentMap = parent.inheritableThreadLocals; 717 if (parentMap != null && parentMap.size() > 0) { 718 this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parentMap); 719 } 720 if (VM.isBooted()) { 721 this.contextClassLoader = parent.getContextClassLoader(); 722 } 723 } else if (VM.isBooted()) { 724 // default CCL to the system class loader when not inheriting 725 this.contextClassLoader = ClassLoader.getSystemClassLoader(); 726 } 727 } 728 729 // special value to indicate this is a newly-created Thread 730 // Note that his must match the declaration in ScopedValue. 731 this.scopedValueBindings = NEW_THREAD_BINDINGS; 732 } 733 734 /** 735 * Initializes a virtual Thread. 736 * 737 * @param name thread name, can be null 738 * @param characteristics thread characteristics 739 * @param bound true when bound to an OS thread 740 */ 741 Thread(String name, int characteristics, boolean bound) { 742 this.tid = ThreadIdentifiers.next(); 743 this.name = (name != null) ? name : ""; 744 745 // thread locals 746 if ((characteristics & NO_INHERIT_THREAD_LOCALS) == 0) { 747 Thread parent = currentThread(); 748 ThreadLocal.ThreadLocalMap parentMap = parent.inheritableThreadLocals; 749 if (parentMap != null && parentMap.size() > 0) { 750 this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parentMap); 751 } 752 this.contextClassLoader = parent.getContextClassLoader(); 753 } else { 754 // default CCL to the system class loader when not inheriting 755 this.contextClassLoader = ClassLoader.getSystemClassLoader(); 756 } 757 758 // special value to indicate this is a newly-created Thread 759 this.scopedValueBindings = NEW_THREAD_BINDINGS; 760 761 // create a FieldHolder object, needed when bound to an OS thread 762 if (bound) { 763 ThreadGroup g = Constants.VTHREAD_GROUP; 764 int pri = NORM_PRIORITY; 765 this.holder = new FieldHolder(g, null, -1, pri, true); 766 } else { 767 this.holder = null; 768 } 769 } 770 771 /** 772 * Returns a builder for creating a platform {@code Thread} or {@code ThreadFactory} 773 * that creates platform threads. 774 * 775 * @apiNote The following are examples using the builder: 776 * {@snippet : 777 * // Start a daemon thread to run a task 778 * Thread thread = Thread.ofPlatform().daemon().start(runnable); 779 * 780 * // Create an unstarted thread with name "duke", its start() method 781 * // must be invoked to schedule it to execute. 782 * Thread thread = Thread.ofPlatform().name("duke").unstarted(runnable); 783 * 784 * // A ThreadFactory that creates daemon threads named "worker-0", "worker-1", ... 785 * ThreadFactory factory = Thread.ofPlatform().daemon().name("worker-", 0).factory(); 786 * } 787 * 788 * @return A builder for creating {@code Thread} or {@code ThreadFactory} objects. 789 * @since 21 790 */ 791 public static Builder.OfPlatform ofPlatform() { 792 return new ThreadBuilders.PlatformThreadBuilder(); 793 } 794 795 /** 796 * Returns a builder for creating a virtual {@code Thread} or {@code ThreadFactory} 797 * that creates virtual threads. 798 * 799 * @apiNote The following are examples using the builder: 800 * {@snippet : 801 * // Start a virtual thread to run a task. 802 * Thread thread = Thread.ofVirtual().start(runnable); 803 * 804 * // A ThreadFactory that creates virtual threads 805 * ThreadFactory factory = Thread.ofVirtual().factory(); 806 * } 807 * 808 * @return A builder for creating {@code Thread} or {@code ThreadFactory} objects. 809 * @since 21 810 */ 811 public static Builder.OfVirtual ofVirtual() { 812 return new ThreadBuilders.VirtualThreadBuilder(); 813 } 814 815 /** 816 * A builder for {@link Thread} and {@link ThreadFactory} objects. 817 * 818 * <p> {@code Builder} defines methods to set {@code Thread} properties such 819 * as the thread {@link #name(String) name}. This includes properties that would 820 * otherwise be <a href="Thread.html#inheritance">inherited</a>. Once set, a 821 * {@code Thread} or {@code ThreadFactory} is created with the following methods: 822 * 823 * <ul> 824 * <li> The {@linkplain #unstarted(Runnable) unstarted} method creates a new 825 * <em>unstarted</em> {@code Thread} to run a task. The {@code Thread}'s 826 * {@link Thread#start() start} method must be invoked to schedule the 827 * thread to execute. 828 * <li> The {@linkplain #start(Runnable) start} method creates a new {@code 829 * Thread} to run a task and schedules the thread to execute. 830 * <li> The {@linkplain #factory() factory} method creates a {@code ThreadFactory}. 831 * </ul> 832 * 833 * <p> A {@code Thread.Builder} is not thread safe. The {@code ThreadFactory} 834 * returned by the builder's {@code factory()} method is thread safe. 835 * 836 * <p> Unless otherwise specified, passing a null argument to a method in 837 * this interface causes a {@code NullPointerException} to be thrown. 838 * 839 * @see Thread#ofPlatform() 840 * @see Thread#ofVirtual() 841 * @since 21 842 */ 843 public sealed interface Builder 844 permits Builder.OfPlatform, Builder.OfVirtual { 845 846 /** 847 * Sets the thread name. 848 * @param name thread name 849 * @return this builder 850 */ 851 Builder name(String name); 852 853 /** 854 * Sets the thread name to be the concatenation of a string prefix and 855 * the string representation of a counter value. The counter's initial 856 * value is {@code start}. It is incremented after a {@code Thread} is 857 * created with this builder so that the next thread is named with 858 * the new counter value. A {@code ThreadFactory} created with this 859 * builder is seeded with the current value of the counter. The {@code 860 * ThreadFactory} increments its copy of the counter after {@link 861 * ThreadFactory#newThread(Runnable) newThread} is used to create a 862 * {@code Thread}. 863 * 864 * @apiNote 865 * The following example creates a builder that is invoked twice to start 866 * two threads named "{@code worker-0}" and "{@code worker-1}". 867 * {@snippet : 868 * Thread.Builder builder = Thread.ofPlatform().name("worker-", 0); 869 * Thread t1 = builder.start(task1); // name "worker-0" 870 * Thread t2 = builder.start(task2); // name "worker-1" 871 * } 872 * 873 * @param prefix thread name prefix 874 * @param start the starting value of the counter 875 * @return this builder 876 * @throws IllegalArgumentException if start is negative 877 */ 878 Builder name(String prefix, long start); 879 880 /** 881 * Sets whether the thread inherits the initial values of {@linkplain 882 * InheritableThreadLocal inheritable-thread-local} variables from the 883 * constructing thread. The default is to inherit. 884 * 885 * @param inherit {@code true} to inherit, {@code false} to not inherit 886 * @return this builder 887 */ 888 Builder inheritInheritableThreadLocals(boolean inherit); 889 890 /** 891 * Sets the uncaught exception handler. 892 * @param ueh uncaught exception handler 893 * @return this builder 894 */ 895 Builder uncaughtExceptionHandler(UncaughtExceptionHandler ueh); 896 897 /** 898 * Creates a new {@code Thread} from the current state of the builder to 899 * run the given task. The {@code Thread}'s {@link Thread#start() start} 900 * method must be invoked to schedule the thread to execute. 901 * 902 * @param task the object to run when the thread executes 903 * @return a new unstarted Thread 904 * 905 * @see <a href="Thread.html#inheritance">Inheritance when creating threads</a> 906 */ 907 Thread unstarted(Runnable task); 908 909 /** 910 * Creates a new {@code Thread} from the current state of the builder and 911 * schedules it to execute. 912 * 913 * @param task the object to run when the thread executes 914 * @return a new started Thread 915 * 916 * @see <a href="Thread.html#inheritance">Inheritance when creating threads</a> 917 */ 918 Thread start(Runnable task); 919 920 /** 921 * Returns a {@code ThreadFactory} to create threads from the current 922 * state of the builder. The returned thread factory is safe for use by 923 * multiple concurrent threads. 924 * 925 * @return a thread factory to create threads 926 */ 927 ThreadFactory factory(); 928 929 /** 930 * A builder for creating a platform {@link Thread} or {@link ThreadFactory} 931 * that creates platform threads. 932 * 933 * <p> Unless otherwise specified, passing a null argument to a method in 934 * this interface causes a {@code NullPointerException} to be thrown. 935 * 936 * @see Thread#ofPlatform() 937 * @since 21 938 */ 939 sealed interface OfPlatform extends Builder 940 permits ThreadBuilders.PlatformThreadBuilder { 941 942 @Override OfPlatform name(String name); 943 944 /** 945 * @throws IllegalArgumentException {@inheritDoc} 946 */ 947 @Override OfPlatform name(String prefix, long start); 948 949 @Override OfPlatform inheritInheritableThreadLocals(boolean inherit); 950 @Override OfPlatform uncaughtExceptionHandler(UncaughtExceptionHandler ueh); 951 952 /** 953 * Sets the thread group. 954 * @param group the thread group 955 * @return this builder 956 */ 957 OfPlatform group(ThreadGroup group); 958 959 /** 960 * Sets the daemon status. 961 * @param on {@code true} to create daemon threads 962 * @return this builder 963 */ 964 OfPlatform daemon(boolean on); 965 966 /** 967 * Sets the daemon status to {@code true}. 968 * @implSpec The default implementation invokes {@linkplain #daemon(boolean)} with 969 * a value of {@code true}. 970 * @return this builder 971 */ 972 default OfPlatform daemon() { 973 return daemon(true); 974 } 975 976 /** 977 * Sets the thread priority. 978 * @param priority priority 979 * @return this builder 980 * @throws IllegalArgumentException if the priority is less than 981 * {@link Thread#MIN_PRIORITY} or greater than {@link Thread#MAX_PRIORITY} 982 */ 983 OfPlatform priority(int priority); 984 985 /** 986 * Sets the desired stack size. 987 * 988 * <p> The stack size is the approximate number of bytes of address space 989 * that the Java virtual machine is to allocate for the thread's stack. The 990 * effect is highly platform dependent and the Java virtual machine is free 991 * to treat the {@code stackSize} parameter as a "suggestion". If the value 992 * is unreasonably low for the platform then a platform specific minimum 993 * may be used. If the value is unreasonably high then a platform specific 994 * maximum may be used. A value of zero is always ignored. 995 * 996 * @param stackSize the desired stack size 997 * @return this builder 998 * @throws IllegalArgumentException if the stack size is negative 999 */ 1000 OfPlatform stackSize(long stackSize); 1001 } 1002 1003 /** 1004 * A builder for creating a virtual {@link Thread} or {@link ThreadFactory} 1005 * that creates virtual threads. 1006 * 1007 * <p> Unless otherwise specified, passing a null argument to a method in 1008 * this interface causes a {@code NullPointerException} to be thrown. 1009 * 1010 * @see Thread#ofVirtual() 1011 * @since 21 1012 */ 1013 sealed interface OfVirtual extends Builder 1014 permits ThreadBuilders.VirtualThreadBuilder { 1015 1016 @Override OfVirtual name(String name); 1017 1018 /** 1019 * @throws IllegalArgumentException {@inheritDoc} 1020 */ 1021 @Override OfVirtual name(String prefix, long start); 1022 1023 @Override OfVirtual inheritInheritableThreadLocals(boolean inherit); 1024 @Override OfVirtual uncaughtExceptionHandler(UncaughtExceptionHandler ueh); 1025 } 1026 } 1027 1028 /** 1029 * Throws CloneNotSupportedException as a Thread can not be meaningfully 1030 * cloned. Construct a new Thread instead. 1031 * 1032 * @throws CloneNotSupportedException 1033 * always 1034 */ 1035 @Override 1036 protected Object clone() throws CloneNotSupportedException { 1037 throw new CloneNotSupportedException(); 1038 } 1039 1040 /** 1041 * Helper class for auto-numbering platform threads. The numbers start at 1042 * 0 and are separate from the thread identifier for historical reasons. 1043 */ 1044 private static class ThreadNumbering { 1045 private static final Unsafe U; 1046 private static final Object NEXT_BASE; 1047 private static final long NEXT_OFFSET; 1048 static { 1049 U = Unsafe.getUnsafe(); 1050 try { 1051 Field nextField = ThreadNumbering.class.getDeclaredField("next"); 1052 NEXT_BASE = U.staticFieldBase(nextField); 1053 NEXT_OFFSET = U.staticFieldOffset(nextField); 1054 } catch (NoSuchFieldException e) { 1055 throw new ExceptionInInitializerError(e); 1056 } 1057 } 1058 private static volatile int next; 1059 static int next() { 1060 return U.getAndAddInt(NEXT_BASE, NEXT_OFFSET, 1); 1061 } 1062 } 1063 1064 /** 1065 * Generates a thread name of the form {@code Thread-<n>}. 1066 */ 1067 static String genThreadName() { 1068 return "Thread-" + ThreadNumbering.next(); 1069 } 1070 1071 /** 1072 * Throws NullPointerException if the name is null. Avoids use of 1073 * Objects.requireNonNull in early startup. 1074 */ 1075 private static String checkName(String name) { 1076 if (name == null) 1077 throw new NullPointerException("'name' is null"); 1078 return name; 1079 } 1080 1081 /** 1082 * Initializes a new platform {@code Thread}. This constructor has the same 1083 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 1084 * {@code (null, null, gname)}, where {@code gname} is a newly generated 1085 * name. Automatically generated names are of the form 1086 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer. 1087 * 1088 * <p> This constructor is only useful when extending {@code Thread} to 1089 * override the {@link #run()} method. 1090 * 1091 * @see <a href="#inheritance">Inheritance when creating threads</a> 1092 */ 1093 public Thread() { 1094 this(null, null, 0, null, 0); 1095 } 1096 1097 /** 1098 * Initializes a new platform {@code Thread}. This constructor has the same 1099 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 1100 * {@code (null, task, gname)}, where {@code gname} is a newly generated 1101 * name. Automatically generated names are of the form 1102 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer. 1103 * 1104 * <p> For a non-null task, invoking this constructor directly is equivalent to: 1105 * <pre>{@code Thread.ofPlatform().unstarted(task); }</pre> 1106 * 1107 * @param task 1108 * the object whose {@code run} method is invoked when this thread 1109 * is started. If {@code null}, this classes {@code run} method does 1110 * nothing. 1111 * 1112 * @see <a href="#inheritance">Inheritance when creating threads</a> 1113 */ 1114 public Thread(Runnable task) { 1115 this(null, null, 0, task, 0); 1116 } 1117 1118 /** 1119 * Initializes a new platform {@code Thread}. This constructor has the same 1120 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 1121 * {@code (group, task, gname)}, where {@code gname} is a newly generated 1122 * name. Automatically generated names are of the form 1123 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer. 1124 * 1125 * <p> For a non-null group and task, invoking this constructor directly is 1126 * equivalent to: 1127 * <pre>{@code Thread.ofPlatform().group(group).unstarted(task); }</pre> 1128 * 1129 * @param group 1130 * the thread group. If {@code null} the group 1131 * is set to the current thread's thread group. 1132 * 1133 * @param task 1134 * the object whose {@code run} method is invoked when this thread 1135 * is started. If {@code null}, this thread's run method is invoked. 1136 * 1137 * @see <a href="#inheritance">Inheritance when creating threads</a> 1138 */ 1139 public Thread(ThreadGroup group, Runnable task) { 1140 this(group, null, 0, task, 0); 1141 } 1142 1143 /** 1144 * Initializes a new platform {@code Thread}. This constructor has the same 1145 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 1146 * {@code (null, null, name)}. 1147 * 1148 * <p> This constructor is only useful when extending {@code Thread} to 1149 * override the {@link #run()} method. 1150 * 1151 * @param name 1152 * the name of the new thread 1153 * 1154 * @see <a href="#inheritance">Inheritance when creating threads</a> 1155 */ 1156 public Thread(String name) { 1157 this(null, checkName(name), 0, null, 0); 1158 } 1159 1160 /** 1161 * Initializes a new platform {@code Thread}. This constructor has the same 1162 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 1163 * {@code (group, null, name)}. 1164 * 1165 * <p> This constructor is only useful when extending {@code Thread} to 1166 * override the {@link #run()} method. 1167 * 1168 * @param group 1169 * the thread group. If {@code null}, the group 1170 * is set to the current thread's thread group. 1171 * 1172 * @param name 1173 * the name of the new thread 1174 * 1175 * @see <a href="#inheritance">Inheritance when creating threads</a> 1176 */ 1177 public Thread(ThreadGroup group, String name) { 1178 this(group, checkName(name), 0, null, 0); 1179 } 1180 1181 /** 1182 * Initializes a new platform {@code Thread}. This constructor has the same 1183 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 1184 * {@code (null, task, name)}. 1185 * 1186 * <p> For a non-null task and name, invoking this constructor directly is 1187 * equivalent to: 1188 * <pre>{@code Thread.ofPlatform().name(name).unstarted(task); }</pre> 1189 * 1190 * @param task 1191 * the object whose {@code run} method is invoked when this thread 1192 * is started. If {@code null}, this thread's run method is invoked. 1193 * 1194 * @param name 1195 * the name of the new thread 1196 * 1197 * @see <a href="#inheritance">Inheritance when creating threads</a> 1198 */ 1199 public Thread(Runnable task, String name) { 1200 this(null, checkName(name), 0, task, 0); 1201 } 1202 1203 /** 1204 * Initializes a new platform {@code Thread} so that it has {@code task} 1205 * as its run object, has the specified {@code name} as its name, 1206 * and belongs to the thread group referred to by {@code group}. 1207 * 1208 * <p>The priority of the newly created thread is the smaller of 1209 * priority of the thread creating it and the maximum permitted 1210 * priority of the thread group. The method {@linkplain #setPriority 1211 * setPriority} may be used to change the priority to a new value. 1212 * 1213 * <p>The newly created thread is initially marked as being a daemon 1214 * thread if and only if the thread creating it is currently marked 1215 * as a daemon thread. The method {@linkplain #setDaemon setDaemon} 1216 * may be used to change whether or not a thread is a daemon. 1217 * 1218 * <p>For a non-null group, task, and name, invoking this constructor directly 1219 * is equivalent to: 1220 * <pre>{@code Thread.ofPlatform().group(group).name(name).unstarted(task); }</pre> 1221 * 1222 * @param group 1223 * the thread group. If {@code null}, the group 1224 * is set to the current thread's thread group. 1225 * 1226 * @param task 1227 * the object whose {@code run} method is invoked when this thread 1228 * is started. If {@code null}, this thread's run method is invoked. 1229 * 1230 * @param name 1231 * the name of the new thread 1232 * 1233 * @see <a href="#inheritance">Inheritance when creating threads</a> 1234 */ 1235 public Thread(ThreadGroup group, Runnable task, String name) { 1236 this(group, checkName(name), 0, task, 0); 1237 } 1238 1239 /** 1240 * Initializes a new platform {@code Thread} so that it has {@code task} 1241 * as its run object, has the specified {@code name} as its name, 1242 * and belongs to the thread group referred to by {@code group}, and has 1243 * the specified <i>stack size</i>. 1244 * 1245 * <p>This constructor is identical to {@link 1246 * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact 1247 * that it allows the thread stack size to be specified. The stack size 1248 * is the approximate number of bytes of address space that the virtual 1249 * machine is to allocate for this thread's stack. <b>The effect of the 1250 * {@code stackSize} parameter, if any, is highly platform dependent.</b> 1251 * 1252 * <p>On some platforms, specifying a higher value for the 1253 * {@code stackSize} parameter may allow a thread to achieve greater 1254 * recursion depth before throwing a {@link StackOverflowError}. 1255 * Similarly, specifying a lower value may allow a greater number of 1256 * threads to exist concurrently without throwing an {@link 1257 * OutOfMemoryError} (or other internal error). The details of 1258 * the relationship between the value of the {@code stackSize} parameter 1259 * and the maximum recursion depth and concurrency level are 1260 * platform-dependent. <b>On some platforms, the value of the 1261 * {@code stackSize} parameter may have no effect whatsoever.</b> 1262 * 1263 * <p>The virtual machine is free to treat the {@code stackSize} 1264 * parameter as a suggestion. If the specified value is unreasonably low 1265 * for the platform, the virtual machine may instead use some 1266 * platform-specific minimum value; if the specified value is unreasonably 1267 * high, the virtual machine may instead use some platform-specific 1268 * maximum. Likewise, the virtual machine is free to round the specified 1269 * value up or down as it sees fit (or to ignore it completely). 1270 * 1271 * <p>Specifying a value of zero for the {@code stackSize} parameter will 1272 * cause this constructor to behave exactly like the 1273 * {@code Thread(ThreadGroup, Runnable, String)} constructor. 1274 * 1275 * <p><i>Due to the platform-dependent nature of the behavior of this 1276 * constructor, extreme care should be exercised in its use. 1277 * The thread stack size necessary to perform a given computation will 1278 * likely vary from one JRE implementation to another. In light of this 1279 * variation, careful tuning of the stack size parameter may be required, 1280 * and the tuning may need to be repeated for each JRE implementation on 1281 * which an application is to run.</i> 1282 * 1283 * <p>Implementation note: Java platform implementers are encouraged to 1284 * document their implementation's behavior with respect to the 1285 * {@code stackSize} parameter. 1286 * 1287 * <p>For a non-null group, task, and name, invoking this constructor directly 1288 * is equivalent to: 1289 * <pre>{@code Thread.ofPlatform().group(group).name(name).stackSize(stackSize).unstarted(task); }</pre> 1290 * 1291 * @param group 1292 * the thread group. If {@code null}, the group 1293 * is set to the current thread's thread group. 1294 * 1295 * @param task 1296 * the object whose {@code run} method is invoked when this thread 1297 * is started. If {@code null}, this thread's run method is invoked. 1298 * 1299 * @param name 1300 * the name of the new thread 1301 * 1302 * @param stackSize 1303 * the desired stack size for the new thread, or zero to indicate 1304 * that this parameter is to be ignored. 1305 * 1306 * @since 1.4 1307 * @see <a href="#inheritance">Inheritance when creating threads</a> 1308 */ 1309 public Thread(ThreadGroup group, Runnable task, String name, long stackSize) { 1310 this(group, checkName(name), 0, task, stackSize); 1311 } 1312 1313 /** 1314 * Initializes a new platform {@code Thread} so that it has {@code task} 1315 * as its run object, has the specified {@code name} as its name, 1316 * belongs to the thread group referred to by {@code group}, has 1317 * the specified {@code stackSize}, and inherits initial values for 1318 * {@linkplain InheritableThreadLocal inheritable thread-local} variables 1319 * if {@code inheritThreadLocals} is {@code true}. 1320 * 1321 * <p> This constructor is identical to {@link 1322 * #Thread(ThreadGroup,Runnable,String,long)} with the added ability to 1323 * suppress, or not, the inheriting of initial values for inheritable 1324 * thread-local variables from the constructing thread. This allows for 1325 * finer grain control over inheritable thread-locals. Care must be taken 1326 * when passing a value of {@code false} for {@code inheritThreadLocals}, 1327 * as it may lead to unexpected behavior if the new thread executes code 1328 * that expects a specific thread-local value to be inherited. 1329 * 1330 * <p> Specifying a value of {@code true} for the {@code inheritThreadLocals} 1331 * parameter will cause this constructor to behave exactly like the 1332 * {@code Thread(ThreadGroup, Runnable, String, long)} constructor. 1333 * 1334 * <p> For a non-null group, task, and name, invoking this constructor directly 1335 * is equivalent to: 1336 * <pre>{@code Thread.ofPlatform() 1337 * .group(group) 1338 * .name(name) 1339 * .stackSize(stackSize) 1340 * .inheritInheritableThreadLocals(inheritInheritableThreadLocals) 1341 * .unstarted(task); }</pre> 1342 * 1343 * @param group 1344 * the thread group. If {@code null}, the group 1345 * is set to the current thread's thread group. 1346 * 1347 * @param task 1348 * the object whose {@code run} method is invoked when this thread 1349 * is started. If {@code null}, this thread's run method is invoked. 1350 * 1351 * @param name 1352 * the name of the new thread 1353 * 1354 * @param stackSize 1355 * the desired stack size for the new thread, or zero to indicate 1356 * that this parameter is to be ignored 1357 * 1358 * @param inheritInheritableThreadLocals 1359 * if {@code true}, inherit initial values for inheritable 1360 * thread-locals from the constructing thread, otherwise no initial 1361 * values are inherited 1362 * 1363 * @since 9 1364 * @see <a href="#inheritance">Inheritance when creating threads</a> 1365 */ 1366 public Thread(ThreadGroup group, Runnable task, String name, 1367 long stackSize, boolean inheritInheritableThreadLocals) { 1368 this(group, checkName(name), 1369 (inheritInheritableThreadLocals ? 0 : NO_INHERIT_THREAD_LOCALS), 1370 task, stackSize); 1371 } 1372 1373 /** 1374 * Creates a virtual thread to execute a task and schedules it to execute. 1375 * 1376 * <p> This method is equivalent to: 1377 * <pre>{@code Thread.ofVirtual().start(task); }</pre> 1378 * 1379 * @param task the object to run when the thread executes 1380 * @return a new, and started, virtual thread 1381 * @see <a href="#inheritance">Inheritance when creating threads</a> 1382 * @since 21 1383 */ 1384 public static Thread startVirtualThread(Runnable task) { 1385 Objects.requireNonNull(task); 1386 var thread = ThreadBuilders.newVirtualThread(null, null, 0, task); 1387 thread.start(); 1388 return thread; 1389 } 1390 1391 /** 1392 * Returns {@code true} if this thread is a virtual thread. A virtual thread 1393 * is scheduled by the Java virtual machine rather than the operating system. 1394 * 1395 * @return {@code true} if this thread is a virtual thread 1396 * 1397 * @since 21 1398 */ 1399 public final boolean isVirtual() { 1400 return (this instanceof BaseVirtualThread); 1401 } 1402 1403 /** 1404 * Schedules this thread to begin execution. The thread will execute 1405 * independently of the current thread. 1406 * 1407 * <p> A thread can be started at most once. In particular, a thread can not 1408 * be restarted after it has terminated. 1409 * 1410 * @throws IllegalThreadStateException if the thread was already started 1411 */ 1412 public void start() { 1413 synchronized (this) { 1414 // zero status corresponds to state "NEW". 1415 if (holder.threadStatus != 0) 1416 throw new IllegalThreadStateException(); 1417 start0(); 1418 } 1419 } 1420 1421 /** 1422 * Schedules this thread to begin execution in the given thread container. 1423 * @throws IllegalStateException if the container is shutdown or closed 1424 * @throws IllegalThreadStateException if the thread has already been started 1425 */ 1426 void start(ThreadContainer container) { 1427 synchronized (this) { 1428 // zero status corresponds to state "NEW". 1429 if (holder.threadStatus != 0) 1430 throw new IllegalThreadStateException(); 1431 1432 // bind thread to container 1433 if (this.container != null) 1434 throw new IllegalThreadStateException(); 1435 setThreadContainer(container); 1436 1437 // start thread 1438 boolean started = false; 1439 container.add(this); // may throw 1440 try { 1441 // scoped values may be inherited 1442 inheritScopedValueBindings(container); 1443 1444 start0(); 1445 started = true; 1446 } finally { 1447 if (!started) { 1448 container.remove(this); 1449 } 1450 } 1451 } 1452 } 1453 1454 private native void start0(); 1455 1456 /** 1457 * This method is run by the thread when it executes. Subclasses of {@code 1458 * Thread} may override this method. 1459 * 1460 * <p> This method is not intended to be invoked directly. If this thread is a 1461 * platform thread created with a {@link Runnable} task then invoking this method 1462 * will invoke the task's {@code run} method. If this thread is a virtual thread 1463 * then invoking this method directly does nothing. 1464 * 1465 * @implSpec The default implementation executes the {@link Runnable} task that 1466 * the {@code Thread} was created with. If the thread was created without a task 1467 * then this method does nothing. 1468 */ 1469 @Override 1470 public void run() { 1471 Runnable task = holder.task; 1472 if (task != null) { 1473 Object bindings = scopedValueBindings(); 1474 runWith(bindings, task); 1475 } 1476 } 1477 1478 /** 1479 * The VM recognizes this method as special, so any changes to the 1480 * name or signature require corresponding changes in 1481 * JVM_FindScopedValueBindings(). 1482 */ 1483 @Hidden 1484 @ForceInline 1485 final void runWith(Object bindings, Runnable op) { 1486 ensureMaterializedForStackWalk(bindings); 1487 op.run(); 1488 Reference.reachabilityFence(bindings); 1489 } 1490 1491 /** 1492 * Null out reference after Thread termination. 1493 */ 1494 void clearReferences() { 1495 threadLocals = null; 1496 inheritableThreadLocals = null; 1497 if (uncaughtExceptionHandler != null) 1498 uncaughtExceptionHandler = null; 1499 if (nioBlocker != null) 1500 nioBlocker = null; 1501 } 1502 1503 /** 1504 * This method is called by the VM to give a Thread 1505 * a chance to clean up before it actually exits. 1506 */ 1507 private void exit() { 1508 try { 1509 // pop any remaining scopes from the stack, this may block 1510 if (headStackableScopes != null) { 1511 StackableScope.popAll(); 1512 } 1513 } finally { 1514 // notify container that thread is exiting 1515 ThreadContainer container = threadContainer(); 1516 if (container != null) { 1517 container.remove(this); 1518 } 1519 } 1520 1521 try { 1522 if (terminatingThreadLocals() != null) { 1523 TerminatingThreadLocal.threadTerminated(); 1524 } 1525 } finally { 1526 clearReferences(); 1527 } 1528 } 1529 1530 /** 1531 * Throws {@code UnsupportedOperationException}. 1532 * 1533 * @throws UnsupportedOperationException always 1534 * 1535 * @deprecated This method was originally specified to "stop" a victim 1536 * thread by causing the victim thread to throw a {@link ThreadDeath}. 1537 * It was inherently unsafe. Stopping a thread caused it to unlock 1538 * all of the monitors that it had locked (as a natural consequence 1539 * of the {@code ThreadDeath} exception propagating up the stack). If 1540 * any of the objects previously protected by these monitors were in 1541 * an inconsistent state, the damaged objects became visible to 1542 * other threads, potentially resulting in arbitrary behavior. 1543 * Usages of {@code stop} should be replaced by code that simply 1544 * modifies some variable to indicate that the target thread should 1545 * stop running. The target thread should check this variable 1546 * regularly, and return from its run method in an orderly fashion 1547 * if the variable indicates that it is to stop running. If the 1548 * target thread waits for long periods (on a condition variable, 1549 * for example), the {@code interrupt} method should be used to 1550 * interrupt the wait. 1551 * For more information, see 1552 * <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why 1553 * is Thread.stop deprecated and the ability to stop a thread removed?</a>. 1554 */ 1555 @Deprecated(since="1.2", forRemoval=true) 1556 public final void stop() { 1557 throw new UnsupportedOperationException(); 1558 } 1559 1560 /** 1561 * Interrupts this thread. 1562 * 1563 * <p> If this thread is blocked in an invocation of the {@link 1564 * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link 1565 * Object#wait(long, int) wait(long, int)} methods of the {@link Object} 1566 * class, or of the {@link #join()}, {@link #join(long)}, {@link 1567 * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)} 1568 * methods of this class, then its interrupt status will be cleared and it 1569 * will receive an {@link InterruptedException}. 1570 * 1571 * <p> If this thread is blocked in an I/O operation upon an {@link 1572 * java.nio.channels.InterruptibleChannel InterruptibleChannel} 1573 * then the channel will be closed, the thread's interrupt 1574 * status will be set, and the thread will receive a {@link 1575 * java.nio.channels.ClosedByInterruptException}. 1576 * 1577 * <p> If this thread is blocked in a {@link java.nio.channels.Selector} 1578 * then the thread's interrupt status will be set and it will return 1579 * immediately from the selection operation, possibly with a non-zero 1580 * value, just as if the selector's {@link 1581 * java.nio.channels.Selector#wakeup wakeup} method were invoked. 1582 * 1583 * <p> If none of the previous conditions hold then this thread's interrupt 1584 * status will be set. </p> 1585 * 1586 * <p> Interrupting a thread that is not alive need not have any effect. 1587 * 1588 * @implNote In the JDK Reference Implementation, interruption of a thread 1589 * that is not alive still records that the interrupt request was made and 1590 * will report it via {@link #interrupted()} and {@link #isInterrupted()}. 1591 */ 1592 public void interrupt() { 1593 // Setting the interrupt status must be done before reading nioBlocker. 1594 interrupted = true; 1595 interrupt0(); // inform VM of interrupt 1596 1597 // thread may be blocked in an I/O operation 1598 if (this != Thread.currentThread()) { 1599 Interruptible blocker; 1600 synchronized (interruptLock) { 1601 blocker = nioBlocker; 1602 if (blocker != null) { 1603 blocker.interrupt(this); 1604 } 1605 } 1606 if (blocker != null) { 1607 blocker.postInterrupt(); 1608 } 1609 } 1610 } 1611 1612 /** 1613 * Tests whether the current thread has been interrupted. The 1614 * <i>interrupted status</i> of the thread is cleared by this method. In 1615 * other words, if this method were to be called twice in succession, the 1616 * second call would return false (unless the current thread were 1617 * interrupted again, after the first call had cleared its interrupted 1618 * status and before the second call had examined it). 1619 * 1620 * @return {@code true} if the current thread has been interrupted; 1621 * {@code false} otherwise. 1622 * @see #isInterrupted() 1623 */ 1624 public static boolean interrupted() { 1625 return currentThread().getAndClearInterrupt(); 1626 } 1627 1628 /** 1629 * Tests whether this thread has been interrupted. The <i>interrupted 1630 * status</i> of the thread is unaffected by this method. 1631 * 1632 * @return {@code true} if this thread has been interrupted; 1633 * {@code false} otherwise. 1634 * @see #interrupted() 1635 */ 1636 public boolean isInterrupted() { 1637 return interrupted; 1638 } 1639 1640 final void setInterrupt() { 1641 // assert Thread.currentCarrierThread() == this; 1642 if (!interrupted) { 1643 interrupted = true; 1644 interrupt0(); // inform VM of interrupt 1645 } 1646 } 1647 1648 final void clearInterrupt() { 1649 // assert Thread.currentCarrierThread() == this; 1650 if (interrupted) { 1651 interrupted = false; 1652 clearInterruptEvent(); 1653 } 1654 } 1655 1656 boolean getAndClearInterrupt() { 1657 boolean oldValue = interrupted; 1658 // We may have been interrupted the moment after we read the field, 1659 // so only clear the field if we saw that it was set and will return 1660 // true; otherwise we could lose an interrupt. 1661 if (oldValue) { 1662 interrupted = false; 1663 clearInterruptEvent(); 1664 } 1665 return oldValue; 1666 } 1667 1668 /** 1669 * Tests if this thread is alive. A thread is alive if it has 1670 * been started and has not yet terminated. 1671 * 1672 * @return {@code true} if this thread is alive; 1673 * {@code false} otherwise. 1674 */ 1675 public final boolean isAlive() { 1676 return alive(); 1677 } 1678 1679 /** 1680 * Returns true if this thread is alive. 1681 * This method is non-final so it can be overridden. 1682 */ 1683 boolean alive() { 1684 return eetop != 0; 1685 } 1686 1687 /** 1688 * Changes the priority of this thread. 1689 * 1690 * For platform threads, the priority is set to the smaller of the specified 1691 * {@code newPriority} and the maximum permitted priority of the thread's 1692 * {@linkplain ThreadGroup thread group}. 1693 * 1694 * The priority of a virtual thread is always {@link Thread#NORM_PRIORITY} 1695 * and {@code newPriority} is ignored. 1696 * 1697 * @param newPriority the new thread priority 1698 * @throws IllegalArgumentException if the priority is not in the 1699 * range {@code MIN_PRIORITY} to {@code MAX_PRIORITY}. 1700 * @see #setPriority(int) 1701 * @see ThreadGroup#getMaxPriority() 1702 */ 1703 public final void setPriority(int newPriority) { 1704 if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) { 1705 throw new IllegalArgumentException(); 1706 } 1707 if (!isVirtual()) { 1708 priority(newPriority); 1709 } 1710 } 1711 1712 void priority(int newPriority) { 1713 ThreadGroup g = holder.group; 1714 if (g != null) { 1715 int maxPriority = g.getMaxPriority(); 1716 if (newPriority > maxPriority) { 1717 newPriority = maxPriority; 1718 } 1719 setPriority0(holder.priority = newPriority); 1720 } 1721 } 1722 1723 /** 1724 * Returns this thread's priority. 1725 * 1726 * <p> The priority of a virtual thread is always {@link Thread#NORM_PRIORITY}. 1727 * 1728 * @return this thread's priority. 1729 * @see #setPriority 1730 */ 1731 public final int getPriority() { 1732 if (isVirtual()) { 1733 return Thread.NORM_PRIORITY; 1734 } else { 1735 return holder.priority; 1736 } 1737 } 1738 1739 /** 1740 * Changes the name of this thread to be equal to the argument {@code name}. 1741 * 1742 * @implNote In the JDK Reference Implementation, if this thread is the 1743 * current thread, and it's a platform thread that was not attached to the 1744 * VM with the Java Native Interface 1745 * <a href="{@docRoot}/../specs/jni/invocation.html#attachcurrentthread"> 1746 * AttachCurrentThread</a> function, then this method will set the operating 1747 * system thread name. This may be useful for debugging and troubleshooting 1748 * purposes. 1749 * 1750 * @param name the new name for this thread. 1751 * 1752 * @spec jni/index.html Java Native Interface Specification 1753 * @see #getName 1754 */ 1755 public final synchronized void setName(String name) { 1756 if (name == null) { 1757 throw new NullPointerException("name cannot be null"); 1758 } 1759 this.name = name; 1760 if (!isVirtual() && Thread.currentThread() == this) { 1761 setNativeName(name); 1762 } 1763 } 1764 1765 /** 1766 * Returns this thread's name. 1767 * 1768 * @return this thread's name. 1769 * @see #setName(String) 1770 */ 1771 public final String getName() { 1772 return name; 1773 } 1774 1775 /** 1776 * Returns the thread's thread group or {@code null} if the thread has 1777 * terminated. 1778 * 1779 * <p> The thread group returned for a virtual thread is the special 1780 * <a href="ThreadGroup.html#virtualthreadgroup"><em>ThreadGroup for 1781 * virtual threads</em></a>. 1782 * 1783 * @return this thread's thread group or {@code null} 1784 */ 1785 public final ThreadGroup getThreadGroup() { 1786 if (isTerminated()) { 1787 return null; 1788 } else { 1789 return isVirtual() ? virtualThreadGroup() : holder.group; 1790 } 1791 } 1792 1793 /** 1794 * Returns an estimate of the number of {@linkplain #isAlive() live} 1795 * platform threads in the current thread's thread group and its subgroups. 1796 * Virtual threads are not included in the estimate. 1797 * 1798 * <p> The value returned is only an estimate because the number of 1799 * threads may change dynamically while this method traverses internal 1800 * data structures, and might be affected by the presence of certain 1801 * system threads. This method is intended primarily for debugging 1802 * and monitoring purposes. 1803 * 1804 * @return an estimate of the number of live platform threads in the 1805 * current thread's thread group and in any other thread group 1806 * that has the current thread's thread group as an ancestor 1807 */ 1808 public static int activeCount() { 1809 return currentThread().getThreadGroup().activeCount(); 1810 } 1811 1812 /** 1813 * Copies into the specified array every {@linkplain #isAlive() live} 1814 * platform thread in the current thread's thread group and its subgroups. 1815 * This method simply invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])} 1816 * method of the current thread's thread group. Virtual threads are 1817 * not enumerated by this method. 1818 * 1819 * <p> An application might use the {@linkplain #activeCount activeCount} 1820 * method to get an estimate of how big the array should be, however 1821 * <i>if the array is too short to hold all the threads, the extra threads 1822 * are silently ignored.</i> If it is critical to obtain every live 1823 * thread in the current thread's thread group and its subgroups, the 1824 * invoker should verify that the returned int value is strictly less 1825 * than the length of {@code tarray}. 1826 * 1827 * <p> Due to the inherent race condition in this method, it is recommended 1828 * that the method only be used for debugging and monitoring purposes. 1829 * 1830 * @param tarray 1831 * an array into which to put the list of threads 1832 * 1833 * @return the number of threads put into the array 1834 */ 1835 public static int enumerate(Thread[] tarray) { 1836 return currentThread().getThreadGroup().enumerate(tarray); 1837 } 1838 1839 /** 1840 * Waits at most {@code millis} milliseconds for this thread to terminate. 1841 * A timeout of {@code 0} means to wait forever. 1842 * This method returns immediately, without waiting, if the thread has not 1843 * been {@link #start() started}. 1844 * 1845 * @implNote 1846 * For platform threads, the implementation uses a loop of {@code this.wait} 1847 * calls conditioned on {@code this.isAlive}. As a thread terminates the 1848 * {@code this.notifyAll} method is invoked. It is recommended that 1849 * applications not use {@code wait}, {@code notify}, or 1850 * {@code notifyAll} on {@code Thread} instances. 1851 * 1852 * @param millis 1853 * the time to wait in milliseconds 1854 * 1855 * @throws IllegalArgumentException 1856 * if the value of {@code millis} is negative 1857 * 1858 * @throws InterruptedException 1859 * if any thread has interrupted the current thread. The 1860 * <i>interrupted status</i> of the current thread is 1861 * cleared when this exception is thrown. 1862 */ 1863 public final void join(long millis) throws InterruptedException { 1864 if (millis < 0) 1865 throw new IllegalArgumentException("timeout value is negative"); 1866 1867 if (this instanceof VirtualThread vthread) { 1868 if (isAlive()) { 1869 long nanos = MILLISECONDS.toNanos(millis); 1870 vthread.joinNanos(nanos); 1871 } 1872 return; 1873 } 1874 1875 synchronized (this) { 1876 if (millis > 0) { 1877 if (isAlive()) { 1878 final long startTime = System.nanoTime(); 1879 long delay = millis; 1880 do { 1881 wait(delay); 1882 } while (isAlive() && (delay = millis - 1883 NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0); 1884 } 1885 } else { 1886 while (isAlive()) { 1887 wait(0); 1888 } 1889 } 1890 } 1891 } 1892 1893 /** 1894 * Waits at most {@code millis} milliseconds plus 1895 * {@code nanos} nanoseconds for this thread to terminate. 1896 * If both arguments are {@code 0}, it means to wait forever. 1897 * This method returns immediately, without waiting, if the thread has not 1898 * been {@link #start() started}. 1899 * 1900 * @implNote 1901 * For platform threads, the implementation uses a loop of {@code this.wait} 1902 * calls conditioned on {@code this.isAlive}. As a thread terminates the 1903 * {@code this.notifyAll} method is invoked. It is recommended that 1904 * applications not use {@code wait}, {@code notify}, or 1905 * {@code notifyAll} on {@code Thread} instances. 1906 * 1907 * @param millis 1908 * the time to wait in milliseconds 1909 * 1910 * @param nanos 1911 * {@code 0-999999} additional nanoseconds to wait 1912 * 1913 * @throws IllegalArgumentException 1914 * if the value of {@code millis} is negative, or the value 1915 * of {@code nanos} is not in the range {@code 0-999999} 1916 * 1917 * @throws InterruptedException 1918 * if any thread has interrupted the current thread. The 1919 * <i>interrupted status</i> of the current thread is 1920 * cleared when this exception is thrown. 1921 */ 1922 public final void join(long millis, int nanos) throws InterruptedException { 1923 if (millis < 0) { 1924 throw new IllegalArgumentException("timeout value is negative"); 1925 } 1926 1927 if (nanos < 0 || nanos > 999999) { 1928 throw new IllegalArgumentException("nanosecond timeout value out of range"); 1929 } 1930 1931 if (this instanceof VirtualThread vthread) { 1932 if (isAlive()) { 1933 // convert arguments to a total in nanoseconds 1934 long totalNanos = MILLISECONDS.toNanos(millis); 1935 totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos); 1936 vthread.joinNanos(totalNanos); 1937 } 1938 return; 1939 } 1940 1941 if (nanos > 0 && millis < Long.MAX_VALUE) { 1942 millis++; 1943 } 1944 join(millis); 1945 } 1946 1947 /** 1948 * Waits for this thread to terminate. 1949 * 1950 * <p> An invocation of this method behaves in exactly the same 1951 * way as the invocation 1952 * 1953 * <blockquote> 1954 * {@linkplain #join(long) join}{@code (0)} 1955 * </blockquote> 1956 * 1957 * @throws InterruptedException 1958 * if any thread has interrupted the current thread. The 1959 * <i>interrupted status</i> of the current thread is 1960 * cleared when this exception is thrown. 1961 */ 1962 public final void join() throws InterruptedException { 1963 join(0); 1964 } 1965 1966 /** 1967 * Waits for this thread to terminate for up to the given waiting duration. 1968 * 1969 * <p> This method does not wait if the duration to wait is less than or 1970 * equal to zero. In this case, the method just tests if the thread has 1971 * terminated. 1972 * 1973 * @param duration 1974 * the maximum duration to wait 1975 * 1976 * @return {@code true} if the thread has terminated, {@code false} if the 1977 * thread has not terminated 1978 * 1979 * @throws InterruptedException 1980 * if the current thread is interrupted while waiting. 1981 * The <i>interrupted status</i> of the current thread is cleared 1982 * when this exception is thrown. 1983 * 1984 * @throws IllegalThreadStateException 1985 * if this thread has not been started. 1986 * 1987 * @since 19 1988 */ 1989 public final boolean join(Duration duration) throws InterruptedException { 1990 long nanos = NANOSECONDS.convert(duration); // MAX_VALUE if > 292 years 1991 1992 Thread.State state = threadState(); 1993 if (state == State.NEW) 1994 throw new IllegalThreadStateException("Thread not started"); 1995 if (state == State.TERMINATED) 1996 return true; 1997 if (nanos <= 0) 1998 return false; 1999 2000 if (this instanceof VirtualThread vthread) { 2001 return vthread.joinNanos(nanos); 2002 } 2003 2004 // convert to milliseconds 2005 long millis = MILLISECONDS.convert(nanos, NANOSECONDS); 2006 if (nanos > NANOSECONDS.convert(millis, MILLISECONDS)) { 2007 millis += 1L; 2008 } 2009 join(millis); 2010 return isTerminated(); 2011 } 2012 2013 /** 2014 * Prints a stack trace of the current thread to the standard error stream. 2015 * This method is useful for debugging. 2016 */ 2017 public static void dumpStack() { 2018 new Exception("Stack trace").printStackTrace(); 2019 } 2020 2021 /** 2022 * Marks this thread as either a <i>daemon</i> or <i>non-daemon</i> thread. 2023 * The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all 2024 * started non-daemon threads have terminated. 2025 * 2026 * <p> The daemon status of a virtual thread is always {@code true} and cannot be 2027 * changed by this method to {@code false}. 2028 * 2029 * <p> This method must be invoked before the thread is started. The behavior 2030 * of this method when the thread has terminated is not specified. 2031 * 2032 * @param on 2033 * if {@code true}, marks this thread as a daemon thread 2034 * 2035 * @throws IllegalArgumentException 2036 * if this is a virtual thread and {@code on} is false 2037 * @throws IllegalThreadStateException 2038 * if this thread is {@linkplain #isAlive alive} 2039 */ 2040 public final void setDaemon(boolean on) { 2041 if (isVirtual() && !on) 2042 throw new IllegalArgumentException("'false' not legal for virtual threads"); 2043 if (isAlive()) 2044 throw new IllegalThreadStateException(); 2045 if (!isVirtual()) 2046 daemon(on); 2047 } 2048 2049 void daemon(boolean on) { 2050 holder.daemon = on; 2051 } 2052 2053 /** 2054 * Tests if this thread is a daemon thread. 2055 * The daemon status of a virtual thread is always {@code true}. 2056 * 2057 * @return {@code true} if this thread is a daemon thread; 2058 * {@code false} otherwise. 2059 * @see #setDaemon(boolean) 2060 */ 2061 public final boolean isDaemon() { 2062 if (isVirtual()) { 2063 return true; 2064 } else { 2065 return holder.daemon; 2066 } 2067 } 2068 2069 /** 2070 * Does nothing. 2071 * 2072 * @deprecated This method originally determined if the currently running 2073 * thread had permission to modify this thread. This method was only useful 2074 * in conjunction with {@linkplain SecurityManager the Security Manager}, 2075 * which is no longer supported. There is no replacement for the Security 2076 * Manager or this method. 2077 */ 2078 @Deprecated(since="17", forRemoval=true) 2079 public final void checkAccess() { } 2080 2081 /** 2082 * Returns a string representation of this thread. The string representation 2083 * will usually include the thread's {@linkplain #threadId() identifier} and 2084 * name. The default implementation for platform threads includes the thread's 2085 * identifier, name, priority, and the name of the thread group. 2086 * 2087 * @return a string representation of this thread. 2088 */ 2089 public String toString() { 2090 StringBuilder sb = new StringBuilder("Thread[#"); 2091 sb.append(threadId()); 2092 sb.append(","); 2093 sb.append(getName()); 2094 sb.append(","); 2095 sb.append(getPriority()); 2096 sb.append(","); 2097 ThreadGroup group = getThreadGroup(); 2098 if (group != null) 2099 sb.append(group.getName()); 2100 sb.append("]"); 2101 return sb.toString(); 2102 } 2103 2104 /** 2105 * Returns the context {@code ClassLoader} for this thread. 2106 * The context {@code ClassLoader} may be set by the creator of the thread 2107 * for use by code running in this thread when loading classes and resources. 2108 * If not {@linkplain #setContextClassLoader set}, the default is to inherit 2109 * the context class loader from the parent thread. 2110 * 2111 * <p> The context {@code ClassLoader} of the primordial thread is typically 2112 * set to the class loader used to load the application. 2113 * 2114 * @return the context {@code ClassLoader} for this thread, or {@code null} 2115 * indicating the system class loader (or, failing that, the 2116 * bootstrap class loader) 2117 * 2118 * @since 1.2 2119 */ 2120 public ClassLoader getContextClassLoader() { 2121 return contextClassLoader; 2122 } 2123 2124 /** 2125 * Sets the context {@code ClassLoader} for this thread. 2126 * 2127 * <p> The context {@code ClassLoader} may be set by the creator of the thread 2128 * for use by code running in this thread when loading classes and resources. 2129 * 2130 * @param cl 2131 * the context ClassLoader for this Thread, or null indicating the 2132 * system class loader (or, failing that, the bootstrap class loader) 2133 * 2134 * @since 1.2 2135 */ 2136 public void setContextClassLoader(ClassLoader cl) { 2137 contextClassLoader = cl; 2138 } 2139 2140 /** 2141 * Returns {@code true} if and only if the current thread holds the 2142 * monitor lock on the specified object. 2143 * 2144 * <p>This method is designed to allow a program to assert that 2145 * the current thread already holds a specified lock: 2146 * <pre> 2147 * assert Thread.holdsLock(obj); 2148 * </pre> 2149 * 2150 * @param obj the object on which to test lock ownership 2151 * @return {@code true} if the current thread holds the monitor lock on 2152 * the specified object. 2153 * @since 1.4 2154 */ 2155 public static native boolean holdsLock(Object obj); 2156 2157 private static final StackTraceElement[] EMPTY_STACK_TRACE 2158 = new StackTraceElement[0]; 2159 2160 /** 2161 * Returns an array of stack trace elements representing the stack dump 2162 * of this thread. This method will return a zero-length array if 2163 * this thread has not started, has started but has not yet been 2164 * scheduled to run by the system, or has terminated. 2165 * If the returned array is of non-zero length then the first element of 2166 * the array represents the top of the stack, which is the most recent 2167 * method invocation in the sequence. The last element of the array 2168 * represents the bottom of the stack, which is the least recent method 2169 * invocation in the sequence. 2170 * 2171 * <p>Some virtual machines may, under some circumstances, omit one 2172 * or more stack frames from the stack trace. In the extreme case, 2173 * a virtual machine that has no stack trace information concerning 2174 * this thread is permitted to return a zero-length array from this 2175 * method. 2176 * 2177 * @return an array of {@code StackTraceElement}, 2178 * each represents one stack frame. 2179 * 2180 * @see Throwable#getStackTrace 2181 * @since 1.5 2182 */ 2183 public StackTraceElement[] getStackTrace() { 2184 if (this != Thread.currentThread()) { 2185 // optimization so we do not call into the vm for threads that 2186 // have not yet started or have terminated 2187 if (!isAlive()) { 2188 return EMPTY_STACK_TRACE; 2189 } 2190 StackTraceElement[] stackTrace = asyncGetStackTrace(); 2191 return (stackTrace != null) ? stackTrace : EMPTY_STACK_TRACE; 2192 } else { 2193 return (new Exception()).getStackTrace(); 2194 } 2195 } 2196 2197 /** 2198 * Returns an array of stack trace elements representing the stack dump of 2199 * this thread. Returns null if the stack trace cannot be obtained. In 2200 * the default implementation, null is returned if the thread is a virtual 2201 * thread that is not mounted or the thread is a platform thread that has 2202 * terminated. 2203 */ 2204 StackTraceElement[] asyncGetStackTrace() { 2205 Object stackTrace = getStackTrace0(); 2206 if (stackTrace == null) { 2207 return null; 2208 } 2209 StackTraceElement[] stes = (StackTraceElement[]) stackTrace; 2210 if (stes.length == 0) { 2211 return null; 2212 } else { 2213 return StackTraceElement.of(stes); 2214 } 2215 } 2216 2217 private native Object getStackTrace0(); 2218 2219 /** 2220 * Returns a map of stack traces for all live platform threads. The map 2221 * does not include virtual threads. 2222 * The map keys are threads and each map value is an array of 2223 * {@code StackTraceElement} that represents the stack dump 2224 * of the corresponding {@code Thread}. 2225 * The returned stack traces are in the format specified for 2226 * the {@link #getStackTrace getStackTrace} method. 2227 * 2228 * <p>The threads may be executing while this method is called. 2229 * The stack trace of each thread only represents a snapshot and 2230 * each stack trace may be obtained at different time. A zero-length 2231 * array will be returned in the map value if the virtual machine has 2232 * no stack trace information about a thread. 2233 * 2234 * @return a {@code Map} from {@code Thread} to an array of 2235 * {@code StackTraceElement} that represents the stack trace of 2236 * the corresponding thread. 2237 * 2238 * @see #getStackTrace 2239 * @see Throwable#getStackTrace 2240 * 2241 * @since 1.5 2242 */ 2243 public static Map<Thread, StackTraceElement[]> getAllStackTraces() { 2244 // Get a snapshot of the list of all threads 2245 Thread[] threads = getThreads(); 2246 StackTraceElement[][] traces = dumpThreads(threads); 2247 Map<Thread, StackTraceElement[]> m = HashMap.newHashMap(threads.length); 2248 for (int i = 0; i < threads.length; i++) { 2249 StackTraceElement[] stackTrace = traces[i]; 2250 if (stackTrace != null) { 2251 m.put(threads[i], stackTrace); 2252 } 2253 // else terminated so we don't put it in the map 2254 } 2255 return m; 2256 } 2257 2258 /** 2259 * Return an array of all live threads. 2260 */ 2261 static Thread[] getAllThreads() { 2262 return getThreads(); 2263 } 2264 2265 private static native StackTraceElement[][] dumpThreads(Thread[] threads); 2266 private static native Thread[] getThreads(); 2267 2268 /** 2269 * Returns the identifier of this Thread. The thread ID is a positive 2270 * {@code long} number generated when this thread was created. 2271 * The thread ID is unique and remains unchanged during its lifetime. 2272 * 2273 * @return this thread's ID 2274 * 2275 * @deprecated This method is not final and may be overridden to return a 2276 * value that is not the thread ID. Use {@link #threadId()} instead. 2277 * 2278 * @since 1.5 2279 */ 2280 @Deprecated(since="19") 2281 public long getId() { 2282 return threadId(); 2283 } 2284 2285 /** 2286 * Returns the identifier of this Thread. The thread ID is a positive 2287 * {@code long} number generated when this thread was created. 2288 * The thread ID is unique and remains unchanged during its lifetime. 2289 * 2290 * @return this thread's ID 2291 * @since 19 2292 */ 2293 public final long threadId() { 2294 return tid; 2295 } 2296 2297 /** 2298 * A thread state. A thread can be in one of the following states: 2299 * <ul> 2300 * <li>{@link #NEW}<br> 2301 * A thread that has not yet started is in this state. 2302 * </li> 2303 * <li>{@link #RUNNABLE}<br> 2304 * A thread executing in the Java virtual machine is in this state. 2305 * </li> 2306 * <li>{@link #BLOCKED}<br> 2307 * A thread that is blocked waiting for a monitor lock 2308 * is in this state. 2309 * </li> 2310 * <li>{@link #WAITING}<br> 2311 * A thread that is waiting indefinitely for another thread to 2312 * perform a particular action is in this state. 2313 * </li> 2314 * <li>{@link #TIMED_WAITING}<br> 2315 * A thread that is waiting for another thread to perform an action 2316 * for up to a specified waiting time is in this state. 2317 * </li> 2318 * <li>{@link #TERMINATED}<br> 2319 * A thread that has exited is in this state. 2320 * </li> 2321 * </ul> 2322 * 2323 * <p> 2324 * A thread can be in only one state at a given point in time. 2325 * These states are virtual machine states which do not reflect 2326 * any operating system thread states. 2327 * 2328 * @since 1.5 2329 * @see #getState 2330 */ 2331 public enum State { 2332 /** 2333 * Thread state for a thread which has not yet started. 2334 */ 2335 NEW, 2336 2337 /** 2338 * Thread state for a runnable thread. A thread in the runnable 2339 * state is executing in the Java virtual machine but it may 2340 * be waiting for other resources from the operating system 2341 * such as processor. 2342 */ 2343 RUNNABLE, 2344 2345 /** 2346 * Thread state for a thread blocked waiting for a monitor lock. 2347 * A thread in the blocked state is waiting for a monitor lock 2348 * to enter a synchronized block/method or 2349 * reenter a synchronized block/method after calling 2350 * {@link Object#wait() Object.wait}. 2351 */ 2352 BLOCKED, 2353 2354 /** 2355 * Thread state for a waiting thread. 2356 * A thread is in the waiting state due to calling one of the 2357 * following methods: 2358 * <ul> 2359 * <li>{@link Object#wait() Object.wait} with no timeout</li> 2360 * <li>{@link #join() Thread.join} with no timeout</li> 2361 * <li>{@link LockSupport#park() LockSupport.park}</li> 2362 * </ul> 2363 * 2364 * <p>A thread in the waiting state is waiting for another thread to 2365 * perform a particular action. 2366 * 2367 * For example, a thread that has called {@code Object.wait()} 2368 * on an object is waiting for another thread to call 2369 * {@code Object.notify()} or {@code Object.notifyAll()} on 2370 * that object. A thread that has called {@code Thread.join()} 2371 * is waiting for a specified thread to terminate. 2372 */ 2373 WAITING, 2374 2375 /** 2376 * Thread state for a waiting thread with a specified waiting time. 2377 * A thread is in the timed waiting state due to calling one of 2378 * the following methods with a specified positive waiting time: 2379 * <ul> 2380 * <li>{@link #sleep Thread.sleep}</li> 2381 * <li>{@link Object#wait(long) Object.wait} with timeout</li> 2382 * <li>{@link #join(long) Thread.join} with timeout</li> 2383 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> 2384 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> 2385 * </ul> 2386 */ 2387 TIMED_WAITING, 2388 2389 /** 2390 * Thread state for a terminated thread. 2391 * The thread has completed execution. 2392 */ 2393 TERMINATED; 2394 } 2395 2396 /** 2397 * Returns the state of this thread. 2398 * This method is designed for use in monitoring of the system state, 2399 * not for synchronization control. 2400 * 2401 * @return this thread's state. 2402 * @since 1.5 2403 */ 2404 public State getState() { 2405 return threadState(); 2406 } 2407 2408 /** 2409 * Returns the state of this thread. 2410 * This method can be used instead of getState as getState is not final and 2411 * so can be overridden to run arbitrary code. 2412 */ 2413 State threadState() { 2414 return jdk.internal.misc.VM.toThreadState(holder.threadStatus); 2415 } 2416 2417 /** 2418 * Returns true if the thread has terminated. 2419 */ 2420 boolean isTerminated() { 2421 return threadState() == State.TERMINATED; 2422 } 2423 2424 /** 2425 * Interface for handlers invoked when a {@code Thread} abruptly 2426 * terminates due to an uncaught exception. 2427 * <p>When a thread is about to terminate due to an uncaught exception 2428 * the Java Virtual Machine will query the thread for its 2429 * {@code UncaughtExceptionHandler} using 2430 * {@link #getUncaughtExceptionHandler} and will invoke the handler's 2431 * {@code uncaughtException} method, passing the thread and the 2432 * exception as arguments. 2433 * If a thread has not had its {@code UncaughtExceptionHandler} 2434 * explicitly set, then its {@code ThreadGroup} object acts as its 2435 * {@code UncaughtExceptionHandler}. If the {@code ThreadGroup} object 2436 * has no 2437 * special requirements for dealing with the exception, it can forward 2438 * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler 2439 * default uncaught exception handler}. 2440 * 2441 * @see #setDefaultUncaughtExceptionHandler 2442 * @see #setUncaughtExceptionHandler 2443 * @see ThreadGroup#uncaughtException 2444 * @since 1.5 2445 */ 2446 @FunctionalInterface 2447 public interface UncaughtExceptionHandler { 2448 /** 2449 * Method invoked when the given thread terminates due to the 2450 * given uncaught exception. 2451 * <p>Any exception thrown by this method will be ignored by the 2452 * Java Virtual Machine. 2453 * @param t the thread 2454 * @param e the exception 2455 */ 2456 void uncaughtException(Thread t, Throwable e); 2457 } 2458 2459 // null unless explicitly set 2460 private volatile UncaughtExceptionHandler uncaughtExceptionHandler; 2461 2462 // null unless explicitly set 2463 private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler; 2464 2465 /** 2466 * Set the default handler invoked when a thread abruptly terminates 2467 * due to an uncaught exception, and no other handler has been defined 2468 * for that thread. 2469 * 2470 * <p>Uncaught exception handling is controlled first by the thread, then 2471 * by the thread's {@link ThreadGroup} object and finally by the default 2472 * uncaught exception handler. If the thread does not have an explicit 2473 * uncaught exception handler set, and the thread's thread group 2474 * (including parent thread groups) does not specialize its 2475 * {@code uncaughtException} method, then the default handler's 2476 * {@code uncaughtException} method will be invoked. 2477 * <p>By setting the default uncaught exception handler, an application 2478 * can change the way in which uncaught exceptions are handled (such as 2479 * logging to a specific device, or file) for those threads that would 2480 * already accept whatever "default" behavior the system 2481 * provided. 2482 * 2483 * <p>Note that the default uncaught exception handler should not usually 2484 * defer to the thread's {@code ThreadGroup} object, as that could cause 2485 * infinite recursion. 2486 * 2487 * @param ueh the object to use as the default uncaught exception handler. 2488 * If {@code null} then there is no default handler. 2489 * 2490 * @see #setUncaughtExceptionHandler 2491 * @see #getUncaughtExceptionHandler 2492 * @see ThreadGroup#uncaughtException 2493 * @since 1.5 2494 */ 2495 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ueh) { 2496 defaultUncaughtExceptionHandler = ueh; 2497 } 2498 2499 /** 2500 * Returns the default handler invoked when a thread abruptly terminates 2501 * due to an uncaught exception. If the returned value is {@code null}, 2502 * there is no default. 2503 * @since 1.5 2504 * @see #setDefaultUncaughtExceptionHandler 2505 * @return the default uncaught exception handler for all threads 2506 */ 2507 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){ 2508 return defaultUncaughtExceptionHandler; 2509 } 2510 2511 /** 2512 * Returns the handler invoked when this thread abruptly terminates 2513 * due to an uncaught exception. If this thread has not had an 2514 * uncaught exception handler explicitly set then this thread's 2515 * {@code ThreadGroup} object is returned, unless this thread 2516 * has terminated, in which case {@code null} is returned. 2517 * @since 1.5 2518 * @return the uncaught exception handler for this thread 2519 */ 2520 public UncaughtExceptionHandler getUncaughtExceptionHandler() { 2521 if (isTerminated()) { 2522 // uncaughtExceptionHandler may be set to null after thread terminates 2523 return null; 2524 } else { 2525 UncaughtExceptionHandler ueh = uncaughtExceptionHandler; 2526 return (ueh != null) ? ueh : getThreadGroup(); 2527 } 2528 } 2529 2530 /** 2531 * Set the handler invoked when this thread abruptly terminates 2532 * due to an uncaught exception. 2533 * <p>A thread can take full control of how it responds to uncaught 2534 * exceptions by having its uncaught exception handler explicitly set. 2535 * If no such handler is set then the thread's {@code ThreadGroup} 2536 * object acts as its handler. 2537 * @param ueh the object to use as this thread's uncaught exception 2538 * handler. If {@code null} then this thread has no explicit handler. 2539 * @see #setDefaultUncaughtExceptionHandler 2540 * @see ThreadGroup#uncaughtException 2541 * @since 1.5 2542 */ 2543 public void setUncaughtExceptionHandler(UncaughtExceptionHandler ueh) { 2544 uncaughtExceptionHandler(ueh); 2545 } 2546 2547 void uncaughtExceptionHandler(UncaughtExceptionHandler ueh) { 2548 uncaughtExceptionHandler = ueh; 2549 } 2550 2551 /** 2552 * Dispatch an uncaught exception to the handler. This method is 2553 * called when a thread terminates with an exception. 2554 */ 2555 void dispatchUncaughtException(Throwable e) { 2556 getUncaughtExceptionHandler().uncaughtException(this, e); 2557 } 2558 2559 /** 2560 * Holder class for constants. 2561 */ 2562 private static class Constants { 2563 // Thread group for virtual threads. 2564 static final ThreadGroup VTHREAD_GROUP; 2565 2566 static { 2567 ThreadGroup root = Thread.currentCarrierThread().getThreadGroup(); 2568 for (ThreadGroup p; (p = root.getParent()) != null; ) { 2569 root = p; 2570 } 2571 VTHREAD_GROUP = new ThreadGroup(root, "VirtualThreads", MAX_PRIORITY, false); 2572 } 2573 } 2574 2575 /** 2576 * Returns the special ThreadGroup for virtual threads. 2577 */ 2578 static ThreadGroup virtualThreadGroup() { 2579 return Constants.VTHREAD_GROUP; 2580 } 2581 2582 // The following three initially uninitialized fields are exclusively 2583 // managed by class java.util.concurrent.ThreadLocalRandom. These 2584 // fields are used to build the high-performance PRNGs in the 2585 // concurrent code. 2586 2587 /** The current seed for a ThreadLocalRandom */ 2588 long threadLocalRandomSeed; 2589 2590 /** Probe hash value; nonzero if threadLocalRandomSeed initialized */ 2591 int threadLocalRandomProbe; 2592 2593 /** Secondary seed isolated from public ThreadLocalRandom sequence */ 2594 int threadLocalRandomSecondarySeed; 2595 2596 /** The thread container that this thread is in */ 2597 private @Stable ThreadContainer container; 2598 ThreadContainer threadContainer() { 2599 return container; 2600 } 2601 void setThreadContainer(ThreadContainer container) { 2602 // assert this.container == null; 2603 this.container = container; 2604 } 2605 2606 /** The top of this stack of stackable scopes owned by this thread */ 2607 private volatile StackableScope headStackableScopes; 2608 StackableScope headStackableScopes() { 2609 return headStackableScopes; 2610 } 2611 static void setHeadStackableScope(StackableScope scope) { 2612 currentThread().headStackableScopes = scope; 2613 } 2614 2615 /* Some private helper methods */ 2616 private native void setPriority0(int newPriority); 2617 private native void interrupt0(); 2618 private static native void clearInterruptEvent(); 2619 private native void setNativeName(String name); 2620 2621 // The address of the next thread identifier, see ThreadIdentifiers. 2622 private static native long getNextThreadIdOffset(); 2623 }