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