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.RejectedExecutionException;
  36 import java.util.concurrent.ThreadFactory;
  37 import java.util.concurrent.StructureViolationException;
  38 import java.util.concurrent.locks.LockSupport;
  39 import jdk.internal.event.ThreadSleepEvent;
  40 import jdk.internal.javac.Restricted;
  41 import jdk.internal.misc.TerminatingThreadLocal;
  42 import jdk.internal.misc.Unsafe;
  43 import jdk.internal.misc.VM;
  44 import jdk.internal.reflect.CallerSensitive;
  45 import jdk.internal.reflect.Reflection;
  46 import jdk.internal.vm.Continuation;
  47 import jdk.internal.vm.ScopedValueContainer;
  48 import jdk.internal.vm.StackableScope;
  49 import jdk.internal.vm.ThreadContainer;
  50 import jdk.internal.vm.annotation.ForceInline;
  51 import jdk.internal.vm.annotation.Hidden;
  52 import jdk.internal.vm.annotation.IntrinsicCandidate;
  53 import jdk.internal.vm.annotation.Stable;
  54 import sun.nio.ch.Interruptible;
  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         // Used by NativeThread for signalling, set lazily, read from any thread
 254         @Stable long nativeThreadID;
 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     long nativeThreadID() {
 283         return holder.nativeThreadID;
 284     }
 285 
 286     void setNativeThreadID(long id) {
 287         holder.nativeThreadID = id;
 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          * @throws RejectedExecutionException if the scheduler cannot accept the task
 821          */
 822         void execute(Thread vthread, Runnable task);
 823 
 824         /**
 825          * {@return a virtual thread scheduler that delegates tasks to the given executor}
 826          * @param executor the executor
 827          */
 828         static VirtualThreadScheduler adapt(Executor executor) {
 829             Objects.requireNonNull(executor);
 830             return (_, task) -> executor.execute(task);
 831         }
 832 
 833         /**
 834          * {@return the virtual thread scheduler for the current virtual thread}
 835          * @throws UnsupportedOperationException if the current thread is not a virtual
 836          * thread or scheduling virtual threads to a user-provided scheduler is not
 837          * supported by this VM
 838          */
 839         @CallerSensitive
 840         @Restricted
 841         static VirtualThreadScheduler current() {
 842             Class<?> caller = Reflection.getCallerClass();
 843             caller.getModule().ensureNativeAccess(VirtualThreadScheduler.class,
 844                     "current",
 845                     caller,
 846                     false);
 847             if (Thread.currentThread() instanceof VirtualThread vthread) {
 848                 return vthread.scheduler(false);
 849             } else {
 850                 throw new UnsupportedOperationException();
 851             }
 852         }
 853     }
 854 
 855     /**
 856      * Returns a builder for creating a platform {@code Thread} or {@code ThreadFactory}
 857      * that creates platform threads.
 858      *
 859      * @apiNote The following are examples using the builder:
 860      * {@snippet :
 861      *   // Start a daemon thread to run a task
 862      *   Thread thread = Thread.ofPlatform().daemon().start(runnable);
 863      *
 864      *   // Create an unstarted thread with name "duke", its start() method
 865      *   // must be invoked to schedule it to execute.
 866      *   Thread thread = Thread.ofPlatform().name("duke").unstarted(runnable);
 867      *
 868      *   // A ThreadFactory that creates daemon threads named "worker-0", "worker-1", ...
 869      *   ThreadFactory factory = Thread.ofPlatform().daemon().name("worker-", 0).factory();
 870      * }
 871      *
 872      * @return A builder for creating {@code Thread} or {@code ThreadFactory} objects.
 873      * @since 21
 874      */
 875     public static Builder.OfPlatform ofPlatform() {
 876         return new ThreadBuilders.PlatformThreadBuilder();
 877     }
 878 
 879     /**
 880      * Returns a builder for creating a virtual {@code Thread} or {@code ThreadFactory}
 881      * that creates virtual threads.
 882      *
 883      * @apiNote The following are examples using the builder:
 884      * {@snippet :
 885      *   // Start a virtual thread to run a task.
 886      *   Thread thread = Thread.ofVirtual().start(runnable);
 887      *
 888      *   // A ThreadFactory that creates virtual threads
 889      *   ThreadFactory factory = Thread.ofVirtual().factory();
 890      * }
 891      *
 892      * @return A builder for creating {@code Thread} or {@code ThreadFactory} objects.
 893      * @since 21
 894      */
 895     public static Builder.OfVirtual ofVirtual() {
 896         return new ThreadBuilders.VirtualThreadBuilder();
 897     }
 898 
 899     /**
 900      * A builder for {@link Thread} and {@link ThreadFactory} objects.
 901      *
 902      * <p> {@code Builder} defines methods to set {@code Thread} properties such
 903      * as the thread {@link #name(String) name}. This includes properties that would
 904      * otherwise be <a href="Thread.html#inheritance">inherited</a>. Once set, a
 905      * {@code Thread} or {@code ThreadFactory} is created with the following methods:
 906      *
 907      * <ul>
 908      *     <li> The {@linkplain #unstarted(Runnable) unstarted} method creates a new
 909      *          <em>unstarted</em> {@code Thread} to run a task. The {@code Thread}'s
 910      *          {@link Thread#start() start} method must be invoked to schedule the
 911      *          thread to execute.
 912      *     <li> The {@linkplain #start(Runnable) start} method creates a new {@code
 913      *          Thread} to run a task and schedules the thread to execute.
 914      *     <li> The {@linkplain #factory() factory} method creates a {@code ThreadFactory}.
 915      * </ul>
 916      *
 917      * <p> A {@code Thread.Builder} is not thread safe. The {@code ThreadFactory}
 918      * returned by the builder's {@code factory()} method is thread safe.
 919      *
 920      * <p> Unless otherwise specified, passing a null argument to a method in
 921      * this interface causes a {@code NullPointerException} to be thrown.
 922      *
 923      * @see Thread#ofPlatform()
 924      * @see Thread#ofVirtual()
 925      * @since 21
 926      */
 927     public sealed interface Builder
 928             permits Builder.OfPlatform, Builder.OfVirtual {
 929 
 930         /**
 931          * Sets the thread name.
 932          * @param name thread name
 933          * @return this builder
 934          */
 935         Builder name(String name);
 936 
 937         /**
 938          * Sets the thread name to be the concatenation of a string prefix and
 939          * the string representation of a counter value. The counter's initial
 940          * value is {@code start}. It is incremented after a {@code Thread} is
 941          * created with this builder so that the next thread is named with
 942          * the new counter value. A {@code ThreadFactory} created with this
 943          * builder is seeded with the current value of the counter. The {@code
 944          * ThreadFactory} increments its copy of the counter after {@link
 945          * ThreadFactory#newThread(Runnable) newThread} is used to create a
 946          * {@code Thread}.
 947          *
 948          * @apiNote
 949          * The following example creates a builder that is invoked twice to start
 950          * two threads named "{@code worker-0}" and "{@code worker-1}".
 951          * {@snippet :
 952          *   Thread.Builder builder = Thread.ofPlatform().name("worker-", 0);
 953          *   Thread t1 = builder.start(task1);   // name "worker-0"
 954          *   Thread t2 = builder.start(task2);   // name "worker-1"
 955          * }
 956          *
 957          * @param prefix thread name prefix
 958          * @param start the starting value of the counter
 959          * @return this builder
 960          * @throws IllegalArgumentException if start is negative
 961          */
 962         Builder name(String prefix, long start);
 963 
 964         /**
 965          * Sets whether the thread inherits the initial values of {@linkplain
 966          * InheritableThreadLocal inheritable-thread-local} variables from the
 967          * constructing thread. The default is to inherit.
 968          *
 969          * @param inherit {@code true} to inherit, {@code false} to not inherit
 970          * @return this builder
 971          */
 972         Builder inheritInheritableThreadLocals(boolean inherit);
 973 
 974         /**
 975          * Sets the uncaught exception handler.
 976          * @param ueh uncaught exception handler
 977          * @return this builder
 978          */
 979         Builder uncaughtExceptionHandler(UncaughtExceptionHandler ueh);
 980 
 981         /**
 982          * Creates a new {@code Thread} from the current state of the builder to
 983          * run the given task. The {@code Thread}'s {@link Thread#start() start}
 984          * method must be invoked to schedule the thread to execute.
 985          *
 986          * @param task the object to run when the thread executes
 987          * @return a new unstarted Thread
 988          *
 989          * @see <a href="Thread.html#inheritance">Inheritance when creating threads</a>
 990          */
 991         Thread unstarted(Runnable task);
 992 
 993         /**
 994          * Creates a new {@code Thread} from the current state of the builder and
 995          * schedules it to execute.
 996          *
 997          * @param task the object to run when the thread executes
 998          * @return a new started Thread
 999          *
1000          * @see <a href="Thread.html#inheritance">Inheritance when creating threads</a>
1001          */
1002         Thread start(Runnable task);
1003 
1004         /**
1005          * Returns a {@code ThreadFactory} to create threads from the current
1006          * state of the builder. The returned thread factory is safe for use by
1007          * multiple concurrent threads.
1008          *
1009          * @return a thread factory to create threads
1010          */
1011         ThreadFactory factory();
1012 
1013         /**
1014          * A builder for creating a platform {@link Thread} or {@link ThreadFactory}
1015          * that creates platform threads.
1016          *
1017          * <p> Unless otherwise specified, passing a null argument to a method in
1018          * this interface causes a {@code NullPointerException} to be thrown.
1019          *
1020          * @see Thread#ofPlatform()
1021          * @since 21
1022          */
1023         sealed interface OfPlatform extends Builder
1024                 permits ThreadBuilders.PlatformThreadBuilder {
1025 
1026             @Override OfPlatform name(String name);
1027 
1028             /**
1029              * @throws IllegalArgumentException {@inheritDoc}
1030              */
1031             @Override OfPlatform name(String prefix, long start);
1032 
1033             @Override OfPlatform inheritInheritableThreadLocals(boolean inherit);
1034             @Override OfPlatform uncaughtExceptionHandler(UncaughtExceptionHandler ueh);
1035 
1036             /**
1037              * Sets the thread group.
1038              * @param group the thread group
1039              * @return this builder
1040              */
1041             OfPlatform group(ThreadGroup group);
1042 
1043             /**
1044              * Sets the daemon status.
1045              * @param on {@code true} to create daemon threads
1046              * @return this builder
1047              */
1048             OfPlatform daemon(boolean on);
1049 
1050             /**
1051              * Sets the daemon status to {@code true}.
1052              * @implSpec The default implementation invokes {@linkplain #daemon(boolean)} with
1053              * a value of {@code true}.
1054              * @return this builder
1055              */
1056             default OfPlatform daemon() {
1057                 return daemon(true);
1058             }
1059 
1060             /**
1061              * Sets the thread priority.
1062              * @param priority priority
1063              * @return this builder
1064              * @throws IllegalArgumentException if the priority is less than
1065              *        {@link Thread#MIN_PRIORITY} or greater than {@link Thread#MAX_PRIORITY}
1066              */
1067             OfPlatform priority(int priority);
1068 
1069             /**
1070              * Sets the desired stack size.
1071              *
1072              * <p> The stack size is the approximate number of bytes of address space
1073              * that the Java virtual machine is to allocate for the thread's stack. The
1074              * effect is highly platform dependent and the Java virtual machine is free
1075              * to treat the {@code stackSize} parameter as a "suggestion". If the value
1076              * is unreasonably low for the platform then a platform specific minimum
1077              * may be used. If the value is unreasonably high then a platform specific
1078              * maximum may be used. A value of zero is always ignored.
1079              *
1080              * @param stackSize the desired stack size
1081              * @return this builder
1082              * @throws IllegalArgumentException if the stack size is negative
1083              */
1084             OfPlatform stackSize(long stackSize);
1085         }
1086 
1087         /**
1088          * A builder for creating a virtual {@link Thread} or {@link ThreadFactory}
1089          * that creates virtual threads.
1090          *
1091          * <p> Unless otherwise specified, passing a null argument to a method in
1092          * this interface causes a {@code NullPointerException} to be thrown.
1093          *
1094          * @see Thread#ofVirtual()
1095          * @since 21
1096          */
1097         sealed interface OfVirtual extends Builder
1098                 permits ThreadBuilders.VirtualThreadBuilder {
1099 
1100             @Override OfVirtual name(String name);
1101 
1102             /**
1103              * @throws IllegalArgumentException {@inheritDoc}
1104              */
1105             @Override OfVirtual name(String prefix, long start);
1106 
1107             @Override OfVirtual inheritInheritableThreadLocals(boolean inherit);
1108             @Override OfVirtual uncaughtExceptionHandler(UncaughtExceptionHandler ueh);
1109 
1110             /**
1111              * Sets the scheduler.
1112              *
1113              * The thread will be scheduled by the Java virtual machine with the given
1114              * scheduler. The scheduler's {@link VirtualThreadScheduler#execute(Thread, Runnable)}
1115              * method may be invoked in the context of a virtual thread. The scheduler
1116              * must arrange to execute the {@code Runnable}'s {@code run} method on a
1117              * platform thread. Attempting to execute the run method in a virtual thread
1118              * causes {@link WrongThreadException} to be thrown.
1119              *
1120              * The {@code execute} method may be invoked at sensitive times (e.g. when
1121              * unparking a thread) so care should be taken to not directly execute the
1122              * task on the <em>current thread</em>.
1123              *
1124              * @param scheduler the scheduler
1125              * @return this builder
1126              * @throws UnsupportedOperationException if scheduling virtual threads to a
1127              *         user-provided scheduler is not supported by this VM
1128              *
1129              * @since 99
1130              */
1131             @CallerSensitive
1132             @Restricted
1133             OfVirtual scheduler(VirtualThreadScheduler scheduler);
1134         }
1135     }
1136 
1137     /**
1138      * Throws CloneNotSupportedException as a Thread can not be meaningfully
1139      * cloned. Construct a new Thread instead.
1140      *
1141      * @throws  CloneNotSupportedException
1142      *          always
1143      */
1144     @Override
1145     protected Object clone() throws CloneNotSupportedException {
1146         throw new CloneNotSupportedException();
1147     }
1148 
1149     /**
1150      * Helper class for auto-numbering platform threads. The numbers start at
1151      * 0 and are separate from the thread identifier for historical reasons.
1152      */
1153     private static class ThreadNumbering {
1154         private static final Unsafe U;
1155         private static final Object NEXT_BASE;
1156         private static final long NEXT_OFFSET;
1157         static {
1158             U = Unsafe.getUnsafe();
1159             try {
1160                 Field nextField = ThreadNumbering.class.getDeclaredField("next");
1161                 NEXT_BASE = U.staticFieldBase(nextField);
1162                 NEXT_OFFSET = U.staticFieldOffset(nextField);
1163             } catch (NoSuchFieldException e) {
1164                 throw new ExceptionInInitializerError(e);
1165             }
1166         }
1167         private static volatile int next;
1168         static int next() {
1169             return U.getAndAddInt(NEXT_BASE, NEXT_OFFSET, 1);
1170         }
1171     }
1172 
1173     /**
1174      * Generates a thread name of the form {@code Thread-<n>}.
1175      */
1176     static String genThreadName() {
1177         return "Thread-" + ThreadNumbering.next();
1178     }
1179 
1180     /**
1181      * Throws NullPointerException if the name is null. Avoids use of
1182      * Objects.requireNonNull in early startup.
1183      */
1184     private static String checkName(String name) {
1185         if (name == null)
1186             throw new NullPointerException("'name' is null");
1187         return name;
1188     }
1189 
1190     /**
1191      * Initializes a new platform {@code Thread}. This constructor has the same
1192      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1193      * {@code (null, null, gname)}, where {@code gname} is a newly generated
1194      * name. Automatically generated names are of the form
1195      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
1196      *
1197      * <p> This constructor is only useful when extending {@code Thread} to
1198      * override the {@link #run()} method.
1199      *
1200      * @see <a href="#inheritance">Inheritance when creating threads</a>
1201      */
1202     public Thread() {
1203         this(null, null, 0, null, 0);
1204     }
1205 
1206     /**
1207      * Initializes a new platform {@code Thread}. This constructor has the same
1208      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1209      * {@code (null, task, gname)}, where {@code gname} is a newly generated
1210      * name. Automatically generated names are of the form
1211      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
1212      *
1213      * <p> For a non-null task, invoking this constructor directly is equivalent to:
1214      * <pre>{@code Thread.ofPlatform().unstarted(task); }</pre>
1215      *
1216      * @param  task
1217      *         the object whose {@code run} method is invoked when this thread
1218      *         is started. If {@code null}, this classes {@code run} method does
1219      *         nothing.
1220      *
1221      * @see <a href="#inheritance">Inheritance when creating threads</a>
1222      */
1223     public Thread(Runnable task) {
1224         this(null, null, 0, task, 0);
1225     }
1226 
1227     /**
1228      * Initializes a new platform {@code Thread}. This constructor has the same
1229      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1230      * {@code (group, task, gname)}, where {@code gname} is a newly generated
1231      * name. Automatically generated names are of the form
1232      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
1233      *
1234      * <p> For a non-null group and task, invoking this constructor directly is
1235      * equivalent to:
1236      * <pre>{@code Thread.ofPlatform().group(group).unstarted(task); }</pre>
1237      *
1238      * @param  group
1239      *         the thread group. If {@code null} the group
1240      *         is set to the current thread's thread group.
1241      *
1242      * @param  task
1243      *         the object whose {@code run} method is invoked when this thread
1244      *         is started. If {@code null}, this thread's run method is invoked.
1245      *
1246      * @see <a href="#inheritance">Inheritance when creating threads</a>
1247      */
1248     public Thread(ThreadGroup group, Runnable task) {
1249         this(group, null, 0, task, 0);
1250     }
1251 
1252     /**
1253      * Initializes a new platform {@code Thread}. This constructor has the same
1254      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1255      * {@code (null, null, name)}.
1256      *
1257      * <p> This constructor is only useful when extending {@code Thread} to
1258      * override the {@link #run()} method.
1259      *
1260      * @param   name
1261      *          the name of the new thread
1262      *
1263      * @see <a href="#inheritance">Inheritance when creating threads</a>
1264      */
1265     public Thread(String name) {
1266         this(null, checkName(name), 0, null, 0);
1267     }
1268 
1269     /**
1270      * Initializes a new platform {@code Thread}. This constructor has the same
1271      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1272      * {@code (group, null, name)}.
1273      *
1274      * <p> This constructor is only useful when extending {@code Thread} to
1275      * override the {@link #run()} method.
1276      *
1277      * @param  group
1278      *         the thread group. If {@code null}, the group
1279      *         is set to the current thread's thread group.
1280      *
1281      * @param  name
1282      *         the name of the new thread
1283      *
1284      * @see <a href="#inheritance">Inheritance when creating threads</a>
1285      */
1286     public Thread(ThreadGroup group, String name) {
1287         this(group, checkName(name), 0, null, 0);
1288     }
1289 
1290     /**
1291      * Initializes a new platform {@code Thread}. This constructor has the same
1292      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1293      * {@code (null, task, name)}.
1294      *
1295      * <p> For a non-null task and name, invoking this constructor directly is
1296      * equivalent to:
1297      * <pre>{@code Thread.ofPlatform().name(name).unstarted(task); }</pre>
1298      *
1299      * @param  task
1300      *         the object whose {@code run} method is invoked when this thread
1301      *         is started. If {@code null}, this thread's run method is invoked.
1302      *
1303      * @param  name
1304      *         the name of the new thread
1305      *
1306      * @see <a href="#inheritance">Inheritance when creating threads</a>
1307      */
1308     public Thread(Runnable task, String name) {
1309         this(null, checkName(name), 0, task, 0);
1310     }
1311 
1312     /**
1313      * Initializes a new platform {@code Thread} so that it has {@code task}
1314      * as its run object, has the specified {@code name} as its name,
1315      * and belongs to the thread group referred to by {@code group}.
1316      *
1317      * <p>The priority of the newly created thread is the smaller of
1318      * priority of the thread creating it and the maximum permitted
1319      * priority of the thread group. The method {@linkplain #setPriority
1320      * setPriority} may be used to change the priority to a new value.
1321      *
1322      * <p>The newly created thread is initially marked as being a daemon
1323      * thread if and only if the thread creating it is currently marked
1324      * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
1325      * may be used to change whether or not a thread is a daemon.
1326      *
1327      * <p>For a non-null group, task, and name, invoking this constructor directly
1328      * is equivalent to:
1329      * <pre>{@code Thread.ofPlatform().group(group).name(name).unstarted(task); }</pre>
1330      *
1331      * @param  group
1332      *         the thread group. If {@code null}, the group
1333      *         is set to the current thread's thread group.
1334      *
1335      * @param  task
1336      *         the object whose {@code run} method is invoked when this thread
1337      *         is started. If {@code null}, this thread's run method is invoked.
1338      *
1339      * @param  name
1340      *         the name of the new thread
1341      *
1342      * @see <a href="#inheritance">Inheritance when creating threads</a>
1343      */
1344     public Thread(ThreadGroup group, Runnable task, String name) {
1345         this(group, checkName(name), 0, task, 0);
1346     }
1347 
1348     /**
1349      * Initializes a new platform {@code Thread} so that it has {@code task}
1350      * as its run object, has the specified {@code name} as its name,
1351      * and belongs to the thread group referred to by {@code group}, and has
1352      * the specified <i>stack size</i>.
1353      *
1354      * <p>This constructor is identical to {@link
1355      * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
1356      * that it allows the thread stack size to be specified.  The stack size
1357      * is the approximate number of bytes of address space that the virtual
1358      * machine is to allocate for this thread's stack.  <b>The effect of the
1359      * {@code stackSize} parameter, if any, is highly platform dependent.</b>
1360      *
1361      * <p>On some platforms, specifying a higher value for the
1362      * {@code stackSize} parameter may allow a thread to achieve greater
1363      * recursion depth before throwing a {@link StackOverflowError}.
1364      * Similarly, specifying a lower value may allow a greater number of
1365      * threads to exist concurrently without throwing an {@link
1366      * OutOfMemoryError} (or other internal error).  The details of
1367      * the relationship between the value of the {@code stackSize} parameter
1368      * and the maximum recursion depth and concurrency level are
1369      * platform-dependent.  <b>On some platforms, the value of the
1370      * {@code stackSize} parameter may have no effect whatsoever.</b>
1371      *
1372      * <p>The virtual machine is free to treat the {@code stackSize}
1373      * parameter as a suggestion.  If the specified value is unreasonably low
1374      * for the platform, the virtual machine may instead use some
1375      * platform-specific minimum value; if the specified value is unreasonably
1376      * high, the virtual machine may instead use some platform-specific
1377      * maximum.  Likewise, the virtual machine is free to round the specified
1378      * value up or down as it sees fit (or to ignore it completely).
1379      *
1380      * <p>Specifying a value of zero for the {@code stackSize} parameter will
1381      * cause this constructor to behave exactly like the
1382      * {@code Thread(ThreadGroup, Runnable, String)} constructor.
1383      *
1384      * <p><i>Due to the platform-dependent nature of the behavior of this
1385      * constructor, extreme care should be exercised in its use.
1386      * The thread stack size necessary to perform a given computation will
1387      * likely vary from one JRE implementation to another.  In light of this
1388      * variation, careful tuning of the stack size parameter may be required,
1389      * and the tuning may need to be repeated for each JRE implementation on
1390      * which an application is to run.</i>
1391      *
1392      * <p>Implementation note: Java platform implementers are encouraged to
1393      * document their implementation's behavior with respect to the
1394      * {@code stackSize} parameter.
1395      *
1396      * <p>For a non-null group, task, and name, invoking this constructor directly
1397      * is equivalent to:
1398      * <pre>{@code Thread.ofPlatform().group(group).name(name).stackSize(stackSize).unstarted(task); }</pre>
1399      *
1400      * @param  group
1401      *         the thread group. If {@code null}, the group
1402      *         is set to the current thread's thread group.
1403      *
1404      * @param  task
1405      *         the object whose {@code run} method is invoked when this thread
1406      *         is started. If {@code null}, this thread's run method is invoked.
1407      *
1408      * @param  name
1409      *         the name of the new thread
1410      *
1411      * @param  stackSize
1412      *         the desired stack size for the new thread, or zero to indicate
1413      *         that this parameter is to be ignored.
1414      *
1415      * @since 1.4
1416      * @see <a href="#inheritance">Inheritance when creating threads</a>
1417      */
1418     public Thread(ThreadGroup group, Runnable task, String name, long stackSize) {
1419         this(group, checkName(name), 0, task, stackSize);
1420     }
1421 
1422     /**
1423      * Initializes a new platform {@code Thread} so that it has {@code task}
1424      * as its run object, has the specified {@code name} as its name,
1425      * belongs to the thread group referred to by {@code group}, has
1426      * the specified {@code stackSize}, and inherits initial values for
1427      * {@linkplain InheritableThreadLocal inheritable thread-local} variables
1428      * if {@code inheritThreadLocals} is {@code true}.
1429      *
1430      * <p> This constructor is identical to {@link
1431      * #Thread(ThreadGroup,Runnable,String,long)} with the added ability to
1432      * suppress, or not, the inheriting of initial values for inheritable
1433      * thread-local variables from the constructing thread. This allows for
1434      * finer grain control over inheritable thread-locals. Care must be taken
1435      * when passing a value of {@code false} for {@code inheritThreadLocals},
1436      * as it may lead to unexpected behavior if the new thread executes code
1437      * that expects a specific thread-local value to be inherited.
1438      *
1439      * <p> Specifying a value of {@code true} for the {@code inheritThreadLocals}
1440      * parameter will cause this constructor to behave exactly like the
1441      * {@code Thread(ThreadGroup, Runnable, String, long)} constructor.
1442      *
1443      * <p> For a non-null group, task, and name, invoking this constructor directly
1444      * is equivalent to:
1445      * <pre>{@code Thread.ofPlatform()
1446      *      .group(group)
1447      *      .name(name)
1448      *      .stackSize(stackSize)
1449      *      .inheritInheritableThreadLocals(inheritInheritableThreadLocals)
1450      *      .unstarted(task); }</pre>
1451      *
1452      * @param  group
1453      *         the thread group. If {@code null}, the group
1454      *         is set to the current thread's thread group.
1455      *
1456      * @param  task
1457      *         the object whose {@code run} method is invoked when this thread
1458      *         is started. If {@code null}, this thread's run method is invoked.
1459      *
1460      * @param  name
1461      *         the name of the new thread
1462      *
1463      * @param  stackSize
1464      *         the desired stack size for the new thread, or zero to indicate
1465      *         that this parameter is to be ignored
1466      *
1467      * @param  inheritInheritableThreadLocals
1468      *         if {@code true}, inherit initial values for inheritable
1469      *         thread-locals from the constructing thread, otherwise no initial
1470      *         values are inherited
1471      *
1472      * @since 9
1473      * @see <a href="#inheritance">Inheritance when creating threads</a>
1474      */
1475     public Thread(ThreadGroup group, Runnable task, String name,
1476                   long stackSize, boolean inheritInheritableThreadLocals) {
1477         this(group, checkName(name),
1478                 (inheritInheritableThreadLocals ? 0 : NO_INHERIT_THREAD_LOCALS),
1479                 task, stackSize);
1480     }
1481 
1482     /**
1483      * Creates a virtual thread to execute a task and schedules it to execute.
1484      * The thread is scheduled by the default virtual thread scheduler.
1485      *
1486      * <p> This method is equivalent to:
1487      * <pre>{@code Thread.ofVirtual().start(task); }</pre>
1488      *
1489      * @param task the object to run when the thread executes
1490      * @return a new, and started, virtual thread
1491      * @see <a href="#inheritance">Inheritance when creating threads</a>
1492      * @since 21
1493      */
1494     public static Thread startVirtualThread(Runnable task) {
1495         Objects.requireNonNull(task);
1496         var thread = ThreadBuilders.newVirtualThread(null, null, 0, task);
1497         thread.start();
1498         return thread;
1499     }
1500 
1501     /**
1502      * Returns {@code true} if this thread is a virtual thread. A virtual thread
1503      * is scheduled by the Java virtual machine rather than the operating system.
1504      *
1505      * @return {@code true} if this thread is a virtual thread
1506      *
1507      * @since 21
1508      */
1509     public final boolean isVirtual() {
1510         return (this instanceof BaseVirtualThread);
1511     }
1512 
1513     /**
1514      * Schedules this thread to begin execution. The thread will execute
1515      * independently of the current thread.
1516      *
1517      * <p> A thread can be started at most once. In particular, a thread can not
1518      * be restarted after it has terminated.
1519      *
1520      * @throws IllegalThreadStateException if the thread was already started
1521      */
1522     public void start() {
1523         synchronized (this) {
1524             // zero status corresponds to state "NEW".
1525             if (holder.threadStatus != 0)
1526                 throw new IllegalThreadStateException();
1527             start0();
1528         }
1529     }
1530 
1531     /**
1532      * Schedules this thread to begin execution in the given thread container.
1533      * @throws IllegalStateException if the container is shutdown or closed
1534      * @throws IllegalThreadStateException if the thread has already been started
1535      */
1536     void start(ThreadContainer container) {
1537         synchronized (this) {
1538             // zero status corresponds to state "NEW".
1539             if (holder.threadStatus != 0)
1540                 throw new IllegalThreadStateException();
1541 
1542             // bind thread to container
1543             if (this.container != null)
1544                 throw new IllegalThreadStateException();
1545             setThreadContainer(container);
1546 
1547             // start thread
1548             boolean started = false;
1549             container.add(this);  // may throw
1550             try {
1551                 // scoped values may be inherited
1552                 inheritScopedValueBindings(container);
1553 
1554                 start0();
1555                 started = true;
1556             } finally {
1557                 if (!started) {
1558                     container.remove(this);
1559                 }
1560             }
1561         }
1562     }
1563 
1564     private native void start0();
1565 
1566     /**
1567      * This method is run by the thread when it executes. Subclasses of {@code
1568      * Thread} may override this method.
1569      *
1570      * <p> This method is not intended to be invoked directly. If this thread is a
1571      * platform thread created with a {@link Runnable} task then invoking this method
1572      * will invoke the task's {@code run} method. If this thread is a virtual thread
1573      * then invoking this method directly does nothing.
1574      *
1575      * @implSpec The default implementation executes the {@link Runnable} task that
1576      * the {@code Thread} was created with. If the thread was created without a task
1577      * then this method does nothing.
1578      */
1579     @Override
1580     public void run() {
1581         Runnable task = holder.task;
1582         if (task != null) {
1583             Object bindings = scopedValueBindings();
1584             runWith(bindings, task);
1585         }
1586     }
1587 
1588     /**
1589      * The VM recognizes this method as special, so any changes to the
1590      * name or signature require corresponding changes in
1591      * JVM_FindScopedValueBindings().
1592      */
1593     @Hidden
1594     @ForceInline
1595     final void runWith(Object bindings, Runnable op) {
1596         ensureMaterializedForStackWalk(bindings);
1597         op.run();
1598         Reference.reachabilityFence(bindings);
1599     }
1600 
1601     /**
1602      * Null out reference after Thread termination.
1603      */
1604     void clearReferences() {
1605         threadLocals = null;
1606         inheritableThreadLocals = null;
1607         if (uncaughtExceptionHandler != null)
1608             uncaughtExceptionHandler = null;
1609         if (nioBlocker != null)
1610             nioBlocker = null;
1611     }
1612 
1613     /**
1614      * This method is called by the VM to give a Thread
1615      * a chance to clean up before it actually exits.
1616      */
1617     private void exit() {
1618         try {
1619             // pop any remaining scopes from the stack, this may block
1620             if (headStackableScopes != null) {
1621                 StackableScope.popAll();
1622             }
1623         } finally {
1624             // notify container that thread is exiting
1625             ThreadContainer container = threadContainer();
1626             if (container != null) {
1627                 container.remove(this);
1628             }
1629         }
1630 
1631         try {
1632             if (terminatingThreadLocals() != null) {
1633                 TerminatingThreadLocal.threadTerminated();
1634             }
1635         } finally {
1636             clearReferences();
1637         }
1638     }
1639 
1640     /**
1641      * Interrupts this thread.
1642      *
1643      * <p> If this thread is blocked in an invocation of the {@link
1644      * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
1645      * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
1646      * class, or of the {@link #join()}, {@link #join(long)}, {@link
1647      * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}
1648      * methods of this class, then its interrupt status will be cleared and it
1649      * will receive an {@link InterruptedException}.
1650      *
1651      * <p> If this thread is blocked in an I/O operation upon an {@link
1652      * java.nio.channels.InterruptibleChannel InterruptibleChannel}
1653      * then the channel will be closed, the thread's interrupt
1654      * status will be set, and the thread will receive a {@link
1655      * java.nio.channels.ClosedByInterruptException}.
1656      *
1657      * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
1658      * then the thread's interrupt status will be set and it will return
1659      * immediately from the selection operation, possibly with a non-zero
1660      * value, just as if the selector's {@link
1661      * java.nio.channels.Selector#wakeup wakeup} method were invoked.
1662      *
1663      * <p> If none of the previous conditions hold then this thread's interrupt
1664      * status will be set. </p>
1665      *
1666      * <p> Interrupting a thread that is not alive need not have any effect.
1667      *
1668      * @implNote In the JDK Reference Implementation, interruption of a thread
1669      * that is not alive still records that the interrupt request was made and
1670      * will report it via {@link #interrupted()} and {@link #isInterrupted()}.
1671      */
1672     public void interrupt() {
1673         // Setting the interrupt status must be done before reading nioBlocker.
1674         interrupted = true;
1675         interrupt0();  // inform VM of interrupt
1676 
1677         // thread may be blocked in an I/O operation
1678         if (this != Thread.currentThread()) {
1679             Interruptible blocker;
1680             synchronized (interruptLock) {
1681                 blocker = nioBlocker;
1682                 if (blocker != null) {
1683                     blocker.interrupt(this);
1684                 }
1685             }
1686             if (blocker != null) {
1687                 blocker.postInterrupt();
1688             }
1689         }
1690     }
1691 
1692     /**
1693      * Tests whether the current thread has been interrupted.  The
1694      * <i>interrupted status</i> of the thread is cleared by this method.  In
1695      * other words, if this method were to be called twice in succession, the
1696      * second call would return false (unless the current thread were
1697      * interrupted again, after the first call had cleared its interrupted
1698      * status and before the second call had examined it).
1699      *
1700      * @return  {@code true} if the current thread has been interrupted;
1701      *          {@code false} otherwise.
1702      * @see #isInterrupted()
1703      */
1704     public static boolean interrupted() {
1705         return currentThread().getAndClearInterrupt();
1706     }
1707 
1708     /**
1709      * Tests whether this thread has been interrupted.  The <i>interrupted
1710      * status</i> of the thread is unaffected by this method.
1711      *
1712      * @return  {@code true} if this thread has been interrupted;
1713      *          {@code false} otherwise.
1714      * @see     #interrupted()
1715      */
1716     public boolean isInterrupted() {
1717         return interrupted;
1718     }
1719 
1720     final void setInterrupt() {
1721         // assert Thread.currentCarrierThread() == this;
1722         if (!interrupted) {
1723             interrupted = true;
1724             interrupt0();  // inform VM of interrupt
1725         }
1726     }
1727 
1728     final void clearInterrupt() {
1729         // assert Thread.currentCarrierThread() == this;
1730         if (interrupted) {
1731             interrupted = false;
1732             clearInterruptEvent();
1733         }
1734     }
1735 
1736     boolean getAndClearInterrupt() {
1737         boolean oldValue = interrupted;
1738         // We may have been interrupted the moment after we read the field,
1739         // so only clear the field if we saw that it was set and will return
1740         // true; otherwise we could lose an interrupt.
1741         if (oldValue) {
1742             interrupted = false;
1743             clearInterruptEvent();
1744         }
1745         return oldValue;
1746     }
1747 
1748     /**
1749      * Tests if this thread is alive. A thread is alive if it has
1750      * been started and has not yet terminated.
1751      *
1752      * @return  {@code true} if this thread is alive;
1753      *          {@code false} otherwise.
1754      */
1755     public final boolean isAlive() {
1756         return alive();
1757     }
1758 
1759     /**
1760      * Returns true if this thread is alive.
1761      * This method is non-final so it can be overridden.
1762      */
1763     boolean alive() {
1764         return eetop != 0;
1765     }
1766 
1767     /**
1768      * Changes the priority of this thread.
1769      *
1770      * For platform threads, the priority is set to the smaller of the specified
1771      * {@code newPriority} and the maximum permitted priority of the thread's
1772      * {@linkplain ThreadGroup thread group}.
1773      *
1774      * The priority of a virtual thread is always {@link Thread#NORM_PRIORITY}
1775      * and {@code newPriority} is ignored.
1776      *
1777      * @param newPriority the new thread priority
1778      * @throws  IllegalArgumentException if the priority is not in the
1779      *          range {@code MIN_PRIORITY} to {@code MAX_PRIORITY}.
1780      * @see #setPriority(int)
1781      * @see ThreadGroup#getMaxPriority()
1782      */
1783     public final void setPriority(int newPriority) {
1784         if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
1785             throw new IllegalArgumentException();
1786         }
1787         if (!isVirtual()) {
1788             priority(newPriority);
1789         }
1790     }
1791 
1792     void priority(int newPriority) {
1793         ThreadGroup g = holder.group;
1794         if (g != null) {
1795             int maxPriority = g.getMaxPriority();
1796             if (newPriority > maxPriority) {
1797                 newPriority = maxPriority;
1798             }
1799             setPriority0(holder.priority = newPriority);
1800         }
1801     }
1802 
1803     /**
1804      * Returns this thread's priority.
1805      *
1806      * <p> The priority of a virtual thread is always {@link Thread#NORM_PRIORITY}.
1807      *
1808      * @return  this thread's priority.
1809      * @see     #setPriority
1810      */
1811     public final int getPriority() {
1812         if (isVirtual()) {
1813             return Thread.NORM_PRIORITY;
1814         } else {
1815             return holder.priority;
1816         }
1817     }
1818 
1819     /**
1820      * Changes the name of this thread to be equal to the argument {@code name}.
1821      *
1822      * @implNote In the JDK Reference Implementation, if this thread is the
1823      * current thread, and it's a platform thread that was not attached to the
1824      * VM with the Java Native Interface
1825      * <a href="{@docRoot}/../specs/jni/invocation.html#attachcurrentthread">
1826      * AttachCurrentThread</a> function, then this method will set the operating
1827      * system thread name. This may be useful for debugging and troubleshooting
1828      * purposes.
1829      *
1830      * @param      name   the new name for this thread.
1831      *
1832      * @spec jni/index.html Java Native Interface Specification
1833      * @see        #getName
1834      */
1835     public final synchronized void setName(String name) {
1836         if (name == null) {
1837             throw new NullPointerException("name cannot be null");
1838         }
1839         this.name = name;
1840         if (!isVirtual() && Thread.currentThread() == this) {
1841             setNativeName(name);
1842         }
1843     }
1844 
1845     /**
1846      * Returns this thread's name.
1847      *
1848      * @return  this thread's name.
1849      * @see     #setName(String)
1850      */
1851     public final String getName() {
1852         return name;
1853     }
1854 
1855     /**
1856      * Returns the thread's thread group or {@code null} if the thread has
1857      * terminated.
1858      *
1859      * <p> The thread group returned for a virtual thread is the special
1860      * <a href="ThreadGroup.html#virtualthreadgroup"><em>ThreadGroup for
1861      * virtual threads</em></a>.
1862      *
1863      * @return  this thread's thread group or {@code null}
1864      */
1865     public final ThreadGroup getThreadGroup() {
1866         if (isTerminated()) {
1867             return null;
1868         } else {
1869             return isVirtual() ? virtualThreadGroup() : holder.group;
1870         }
1871     }
1872 
1873     /**
1874      * Returns an estimate of the number of {@linkplain #isAlive() live}
1875      * platform threads in the current thread's thread group and its subgroups.
1876      * Virtual threads are not included in the estimate.
1877      *
1878      * <p> The value returned is only an estimate because the number of
1879      * threads may change dynamically while this method traverses internal
1880      * data structures, and might be affected by the presence of certain
1881      * system threads. This method is intended primarily for debugging
1882      * and monitoring purposes.
1883      *
1884      * @return  an estimate of the number of live platform threads in the
1885      *          current thread's thread group and in any other thread group
1886      *          that has the current thread's thread group as an ancestor
1887      */
1888     public static int activeCount() {
1889         return currentThread().getThreadGroup().activeCount();
1890     }
1891 
1892     /**
1893      * Copies into the specified array every {@linkplain #isAlive() live}
1894      * platform thread in the current thread's thread group and its subgroups.
1895      * This method simply invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
1896      * method of the current thread's thread group. Virtual threads are
1897      * not enumerated by this method.
1898      *
1899      * <p> An application might use the {@linkplain #activeCount activeCount}
1900      * method to get an estimate of how big the array should be, however
1901      * <i>if the array is too short to hold all the threads, the extra threads
1902      * are silently ignored.</i>  If it is critical to obtain every live
1903      * thread in the current thread's thread group and its subgroups, the
1904      * invoker should verify that the returned int value is strictly less
1905      * than the length of {@code tarray}.
1906      *
1907      * <p> Due to the inherent race condition in this method, it is recommended
1908      * that the method only be used for debugging and monitoring purposes.
1909      *
1910      * @param  tarray
1911      *         an array into which to put the list of threads
1912      *
1913      * @return  the number of threads put into the array
1914      */
1915     public static int enumerate(Thread[] tarray) {
1916         return currentThread().getThreadGroup().enumerate(tarray);
1917     }
1918 
1919     /**
1920      * Waits at most {@code millis} milliseconds for this thread to terminate.
1921      * A timeout of {@code 0} means to wait forever.
1922      * This method returns immediately, without waiting, if the thread has not
1923      * been {@link #start() started}.
1924      *
1925      * @implNote
1926      * For platform threads, the implementation uses a loop of {@code this.wait}
1927      * calls conditioned on {@code this.isAlive}. As a thread terminates the
1928      * {@code this.notifyAll} method is invoked. It is recommended that
1929      * applications not use {@code wait}, {@code notify}, or
1930      * {@code notifyAll} on {@code Thread} instances.
1931      *
1932      * @param  millis
1933      *         the time to wait in milliseconds
1934      *
1935      * @throws  IllegalArgumentException
1936      *          if the value of {@code millis} is negative
1937      *
1938      * @throws  InterruptedException
1939      *          if any thread has interrupted the current thread. The
1940      *          <i>interrupted status</i> of the current thread is
1941      *          cleared when this exception is thrown.
1942      */
1943     public final void join(long millis) throws InterruptedException {
1944         if (millis < 0)
1945             throw new IllegalArgumentException("timeout value is negative");
1946 
1947         if (this instanceof VirtualThread vthread) {
1948             if (isAlive()) {
1949                 long nanos = MILLISECONDS.toNanos(millis);
1950                 vthread.joinNanos(nanos);
1951             }
1952             return;
1953         }
1954 
1955         synchronized (this) {
1956             if (millis > 0) {
1957                 if (isAlive()) {
1958                     final long startTime = System.nanoTime();
1959                     long delay = millis;
1960                     do {
1961                         wait(delay);
1962                     } while (isAlive() && (delay = millis -
1963                              NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
1964                 }
1965             } else {
1966                 while (isAlive()) {
1967                     wait(0);
1968                 }
1969             }
1970         }
1971     }
1972 
1973     /**
1974      * Waits at most {@code millis} milliseconds plus
1975      * {@code nanos} nanoseconds for this thread to terminate.
1976      * If both arguments are {@code 0}, it means to wait forever.
1977      * This method returns immediately, without waiting, if the thread has not
1978      * been {@link #start() started}.
1979      *
1980      * @implNote
1981      * For platform threads, the implementation uses a loop of {@code this.wait}
1982      * calls conditioned on {@code this.isAlive}. As a thread terminates the
1983      * {@code this.notifyAll} method is invoked. It is recommended that
1984      * applications not use {@code wait}, {@code notify}, or
1985      * {@code notifyAll} on {@code Thread} instances.
1986      *
1987      * @param  millis
1988      *         the time to wait in milliseconds
1989      *
1990      * @param  nanos
1991      *         {@code 0-999999} additional nanoseconds to wait
1992      *
1993      * @throws  IllegalArgumentException
1994      *          if the value of {@code millis} is negative, or the value
1995      *          of {@code nanos} is not in the range {@code 0-999999}
1996      *
1997      * @throws  InterruptedException
1998      *          if any thread has interrupted the current thread. The
1999      *          <i>interrupted status</i> of the current thread is
2000      *          cleared when this exception is thrown.
2001      */
2002     public final void join(long millis, int nanos) throws InterruptedException {
2003         if (millis < 0) {
2004             throw new IllegalArgumentException("timeout value is negative");
2005         }
2006 
2007         if (nanos < 0 || nanos > 999999) {
2008             throw new IllegalArgumentException("nanosecond timeout value out of range");
2009         }
2010 
2011         if (this instanceof VirtualThread vthread) {
2012             if (isAlive()) {
2013                 // convert arguments to a total in nanoseconds
2014                 long totalNanos = MILLISECONDS.toNanos(millis);
2015                 totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos);
2016                 vthread.joinNanos(totalNanos);
2017             }
2018             return;
2019         }
2020 
2021         if (nanos > 0 && millis < Long.MAX_VALUE) {
2022             millis++;
2023         }
2024         join(millis);
2025     }
2026 
2027     /**
2028      * Waits for this thread to terminate.
2029      *
2030      * <p> An invocation of this method behaves in exactly the same
2031      * way as the invocation
2032      *
2033      * <blockquote>
2034      * {@linkplain #join(long) join}{@code (0)}
2035      * </blockquote>
2036      *
2037      * @throws  InterruptedException
2038      *          if any thread has interrupted the current thread. The
2039      *          <i>interrupted status</i> of the current thread is
2040      *          cleared when this exception is thrown.
2041      */
2042     public final void join() throws InterruptedException {
2043         join(0);
2044     }
2045 
2046     /**
2047      * Waits for this thread to terminate for up to the given waiting duration.
2048      *
2049      * <p> This method does not wait if the duration to wait is less than or
2050      * equal to zero. In this case, the method just tests if the thread has
2051      * terminated.
2052      *
2053      * @param   duration
2054      *          the maximum duration to wait
2055      *
2056      * @return  {@code true} if the thread has terminated, {@code false} if the
2057      *          thread has not terminated
2058      *
2059      * @throws  InterruptedException
2060      *          if the current thread is interrupted while waiting.
2061      *          The <i>interrupted status</i> of the current thread is cleared
2062      *          when this exception is thrown.
2063      *
2064      * @throws  IllegalThreadStateException
2065      *          if this thread has not been started.
2066      *
2067      * @since 19
2068      */
2069     public final boolean join(Duration duration) throws InterruptedException {
2070         long nanos = NANOSECONDS.convert(duration); // MAX_VALUE if > 292 years
2071 
2072         Thread.State state = threadState();
2073         if (state == State.NEW)
2074             throw new IllegalThreadStateException("Thread not started");
2075         if (state == State.TERMINATED)
2076             return true;
2077         if (nanos <= 0)
2078             return false;
2079 
2080         if (this instanceof VirtualThread vthread) {
2081             return vthread.joinNanos(nanos);
2082         }
2083 
2084         // convert to milliseconds
2085         long millis = MILLISECONDS.convert(nanos, NANOSECONDS);
2086         if (nanos > NANOSECONDS.convert(millis, MILLISECONDS)) {
2087             millis += 1L;
2088         }
2089         join(millis);
2090         return isTerminated();
2091     }
2092 
2093     /**
2094      * Prints a stack trace of the current thread to the standard error stream.
2095      * This method is useful for debugging.
2096      */
2097     public static void dumpStack() {
2098         new Exception("Stack trace").printStackTrace();
2099     }
2100 
2101     /**
2102      * Marks this thread as either a <i>daemon</i> or <i>non-daemon</i> thread.
2103      * The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all
2104      * started non-daemon threads have terminated.
2105      *
2106      * <p> The daemon status of a virtual thread is always {@code true} and cannot be
2107      * changed by this method to {@code false}.
2108      *
2109      * <p> This method must be invoked before the thread is started. The behavior
2110      * of this method when the thread has terminated is not specified.
2111      *
2112      * @param  on
2113      *         if {@code true}, marks this thread as a daemon thread
2114      *
2115      * @throws  IllegalArgumentException
2116      *          if this is a virtual thread and {@code on} is false
2117      * @throws  IllegalThreadStateException
2118      *          if this thread is {@linkplain #isAlive alive}
2119      */
2120     public final void setDaemon(boolean on) {
2121         if (isVirtual() && !on)
2122             throw new IllegalArgumentException("'false' not legal for virtual threads");
2123         if (isAlive())
2124             throw new IllegalThreadStateException();
2125         if (!isVirtual())
2126             daemon(on);
2127     }
2128 
2129     void daemon(boolean on) {
2130         holder.daemon = on;
2131     }
2132 
2133     /**
2134      * Tests if this thread is a daemon thread.
2135      * The daemon status of a virtual thread is always {@code true}.
2136      *
2137      * @return  {@code true} if this thread is a daemon thread;
2138      *          {@code false} otherwise.
2139      * @see     #setDaemon(boolean)
2140      */
2141     public final boolean isDaemon() {
2142         if (isVirtual()) {
2143             return true;
2144         } else {
2145             return holder.daemon;
2146         }
2147     }
2148 
2149     /**
2150      * Does nothing.
2151      *
2152      * @deprecated This method originally determined if the currently running
2153      * thread had permission to modify this thread. This method was only useful
2154      * in conjunction with {@linkplain SecurityManager the Security Manager},
2155      * which is no longer supported. There is no replacement for the Security
2156      * Manager or this method.
2157      */
2158     @Deprecated(since="17", forRemoval=true)
2159     public final void checkAccess() { }
2160 
2161     /**
2162      * Returns a string representation of this thread. The string representation
2163      * will usually include the thread's {@linkplain #threadId() identifier} and
2164      * name. The default implementation for platform threads includes the thread's
2165      * identifier, name, priority, and the name of the thread group.
2166      *
2167      * @return  a string representation of this thread.
2168      */
2169     public String toString() {
2170         StringBuilder sb = new StringBuilder("Thread[#");
2171         sb.append(threadId());
2172         sb.append(",");
2173         sb.append(getName());
2174         sb.append(",");
2175         sb.append(getPriority());
2176         sb.append(",");
2177         ThreadGroup group = getThreadGroup();
2178         if (group != null)
2179             sb.append(group.getName());
2180         sb.append("]");
2181         return sb.toString();
2182     }
2183 
2184     /**
2185      * Returns the context {@code ClassLoader} for this thread.
2186      * The context {@code ClassLoader} may be set by the creator of the thread
2187      * for use by code running in this thread when loading classes and resources.
2188      * If not {@linkplain #setContextClassLoader set}, the default is to inherit
2189      * the context class loader from the parent thread.
2190      *
2191      * <p> The context {@code ClassLoader} of the primordial thread is typically
2192      * set to the class loader used to load the application.
2193      *
2194      * @return  the context {@code ClassLoader} for this thread, or {@code null}
2195      *          indicating the system class loader (or, failing that, the
2196      *          bootstrap class loader)
2197      *
2198      * @since 1.2
2199      */
2200     public ClassLoader getContextClassLoader() {
2201         return contextClassLoader;
2202     }
2203 
2204     /**
2205      * Sets the context {@code ClassLoader} for this thread.
2206      *
2207      * <p> The context {@code ClassLoader} may be set by the creator of the thread
2208      * for use by code running in this thread when loading classes and resources.
2209      *
2210      * @param  cl
2211      *         the context ClassLoader for this Thread, or null  indicating the
2212      *         system class loader (or, failing that, the bootstrap class loader)
2213      *
2214      * @since 1.2
2215      */
2216     public void setContextClassLoader(ClassLoader cl) {
2217         contextClassLoader = cl;
2218     }
2219 
2220     /**
2221      * Returns {@code true} if and only if the current thread holds the
2222      * monitor lock on the specified object.
2223      *
2224      * <p>This method is designed to allow a program to assert that
2225      * the current thread already holds a specified lock:
2226      * <pre>
2227      *     assert Thread.holdsLock(obj);
2228      * </pre>
2229      *
2230      * @param  obj the object on which to test lock ownership
2231      * @return {@code true} if the current thread holds the monitor lock on
2232      *         the specified object.
2233      * @since 1.4
2234      */
2235     public static native boolean holdsLock(Object obj);
2236 
2237     private static final StackTraceElement[] EMPTY_STACK_TRACE
2238         = new StackTraceElement[0];
2239 
2240     /**
2241      * Returns an array of stack trace elements representing the stack dump
2242      * of this thread.  This method will return a zero-length array if
2243      * this thread has not started, has started but has not yet been
2244      * scheduled to run by the system, or has terminated.
2245      * If the returned array is of non-zero length then the first element of
2246      * the array represents the top of the stack, which is the most recent
2247      * method invocation in the sequence.  The last element of the array
2248      * represents the bottom of the stack, which is the least recent method
2249      * invocation in the sequence.
2250      *
2251      * <p>Some virtual machines may, under some circumstances, omit one
2252      * or more stack frames from the stack trace.  In the extreme case,
2253      * a virtual machine that has no stack trace information concerning
2254      * this thread is permitted to return a zero-length array from this
2255      * method.
2256      *
2257      * @return an array of {@code StackTraceElement},
2258      * each represents one stack frame.
2259      *
2260      * @see Throwable#getStackTrace
2261      * @since 1.5
2262      */
2263     public StackTraceElement[] getStackTrace() {
2264         if (this != Thread.currentThread()) {
2265             // optimization so we do not call into the vm for threads that
2266             // have not yet started or have terminated
2267             if (!isAlive()) {
2268                 return EMPTY_STACK_TRACE;
2269             }
2270             StackTraceElement[] stackTrace = asyncGetStackTrace();
2271             return (stackTrace != null) ? stackTrace : EMPTY_STACK_TRACE;
2272         } else {
2273             return (new Exception()).getStackTrace();
2274         }
2275     }
2276 
2277     /**
2278      * Returns an array of stack trace elements representing the stack dump of
2279      * this thread. Returns null if the stack trace cannot be obtained. In
2280      * the default implementation, null is returned if the thread is a virtual
2281      * thread that is not mounted or the thread is a platform thread that has
2282      * terminated.
2283      */
2284     StackTraceElement[] asyncGetStackTrace() {
2285         Object stackTrace = getStackTrace0();
2286         if (stackTrace == null) {
2287             return null;
2288         }
2289         StackTraceElement[] stes = (StackTraceElement[]) stackTrace;
2290         if (stes.length == 0) {
2291             return null;
2292         } else {
2293             return StackTraceElement.of(stes);
2294         }
2295     }
2296 
2297     private native Object getStackTrace0();
2298 
2299     /**
2300      * Returns a map of stack traces for all live platform threads. The map
2301      * does not include virtual threads.
2302      * The map keys are threads and each map value is an array of
2303      * {@code StackTraceElement} that represents the stack dump
2304      * of the corresponding {@code Thread}.
2305      * The returned stack traces are in the format specified for
2306      * the {@link #getStackTrace getStackTrace} method.
2307      *
2308      * <p>The threads may be executing while this method is called.
2309      * The stack trace of each thread only represents a snapshot and
2310      * each stack trace may be obtained at different time.  A zero-length
2311      * array will be returned in the map value if the virtual machine has
2312      * no stack trace information about a thread.
2313      *
2314      * @return a {@code Map} from {@code Thread} to an array of
2315      * {@code StackTraceElement} that represents the stack trace of
2316      * the corresponding thread.
2317      *
2318      * @see #getStackTrace
2319      * @see Throwable#getStackTrace
2320      *
2321      * @since 1.5
2322      */
2323     public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
2324         // Get a snapshot of the list of all threads
2325         Thread[] threads = getThreads();
2326         StackTraceElement[][] traces = dumpThreads(threads);
2327         Map<Thread, StackTraceElement[]> m = HashMap.newHashMap(threads.length);
2328         for (int i = 0; i < threads.length; i++) {
2329             StackTraceElement[] stackTrace = traces[i];
2330             if (stackTrace != null) {
2331                 m.put(threads[i], stackTrace);
2332             }
2333             // else terminated so we don't put it in the map
2334         }
2335         return m;
2336     }
2337 
2338     /**
2339      * Return an array of all live threads.
2340      */
2341     static Thread[] getAllThreads() {
2342         return getThreads();
2343     }
2344 
2345     private static native StackTraceElement[][] dumpThreads(Thread[] threads);
2346     private static native Thread[] getThreads();
2347 
2348     /**
2349      * Returns the identifier of this Thread.  The thread ID is a positive
2350      * {@code long} number generated when this thread was created.
2351      * The thread ID is unique and remains unchanged during its lifetime.
2352      *
2353      * @return this thread's ID
2354      *
2355      * @deprecated This method is not final and may be overridden to return a
2356      * value that is not the thread ID. Use {@link #threadId()} instead.
2357      *
2358      * @since 1.5
2359      */
2360     @Deprecated(since="19")
2361     public long getId() {
2362         return threadId();
2363     }
2364 
2365     /**
2366      * Returns the identifier of this Thread.  The thread ID is a positive
2367      * {@code long} number generated when this thread was created.
2368      * The thread ID is unique and remains unchanged during its lifetime.
2369      *
2370      * @return this thread's ID
2371      * @since 19
2372      */
2373     public final long threadId() {
2374         return tid;
2375     }
2376 
2377     /**
2378      * A thread state.  A thread can be in one of the following states:
2379      * <ul>
2380      * <li>{@link #NEW}<br>
2381      *     A thread that has not yet started is in this state.
2382      *     </li>
2383      * <li>{@link #RUNNABLE}<br>
2384      *     A thread executing in the Java virtual machine is in this state.
2385      *     </li>
2386      * <li>{@link #BLOCKED}<br>
2387      *     A thread that is blocked waiting for a monitor lock
2388      *     is in this state.
2389      *     </li>
2390      * <li>{@link #WAITING}<br>
2391      *     A thread that is waiting indefinitely for another thread to
2392      *     perform a particular action is in this state.
2393      *     </li>
2394      * <li>{@link #TIMED_WAITING}<br>
2395      *     A thread that is waiting for another thread to perform an action
2396      *     for up to a specified waiting time is in this state.
2397      *     </li>
2398      * <li>{@link #TERMINATED}<br>
2399      *     A thread that has exited is in this state.
2400      *     </li>
2401      * </ul>
2402      *
2403      * <p>
2404      * A thread can be in only one state at a given point in time.
2405      * These states are virtual machine states which do not reflect
2406      * any operating system thread states.
2407      *
2408      * @since   1.5
2409      * @see #getState
2410      */
2411     public enum State {
2412         /**
2413          * Thread state for a thread which has not yet started.
2414          */
2415         NEW,
2416 
2417         /**
2418          * Thread state for a runnable thread.  A thread in the runnable
2419          * state is executing in the Java virtual machine but it may
2420          * be waiting for other resources from the operating system
2421          * such as processor.
2422          */
2423         RUNNABLE,
2424 
2425         /**
2426          * Thread state for a thread blocked waiting for a monitor lock.
2427          * A thread in the blocked state is waiting for a monitor lock
2428          * to enter a synchronized block/method or
2429          * reenter a synchronized block/method after calling
2430          * {@link Object#wait() Object.wait}.
2431          */
2432         BLOCKED,
2433 
2434         /**
2435          * Thread state for a waiting thread.
2436          * A thread is in the waiting state due to calling one of the
2437          * following methods:
2438          * <ul>
2439          *   <li>{@link Object#wait() Object.wait} with no timeout</li>
2440          *   <li>{@link #join() Thread.join} with no timeout</li>
2441          *   <li>{@link LockSupport#park() LockSupport.park}</li>
2442          * </ul>
2443          *
2444          * <p>A thread in the waiting state is waiting for another thread to
2445          * perform a particular action.
2446          *
2447          * For example, a thread that has called {@code Object.wait()}
2448          * on an object is waiting for another thread to call
2449          * {@code Object.notify()} or {@code Object.notifyAll()} on
2450          * that object. A thread that has called {@code Thread.join()}
2451          * is waiting for a specified thread to terminate.
2452          */
2453         WAITING,
2454 
2455         /**
2456          * Thread state for a waiting thread with a specified waiting time.
2457          * A thread is in the timed waiting state due to calling one of
2458          * the following methods with a specified positive waiting time:
2459          * <ul>
2460          *   <li>{@link #sleep Thread.sleep}</li>
2461          *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
2462          *   <li>{@link #join(long) Thread.join} with timeout</li>
2463          *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
2464          *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
2465          * </ul>
2466          */
2467         TIMED_WAITING,
2468 
2469         /**
2470          * Thread state for a terminated thread.
2471          * The thread has completed execution.
2472          */
2473         TERMINATED;
2474     }
2475 
2476     /**
2477      * Returns the state of this thread.
2478      * This method is designed for use in monitoring of the system state,
2479      * not for synchronization control.
2480      *
2481      * @return this thread's state.
2482      * @since 1.5
2483      */
2484     public State getState() {
2485         return threadState();
2486     }
2487 
2488     /**
2489      * Returns the state of this thread.
2490      * This method can be used instead of getState as getState is not final and
2491      * so can be overridden to run arbitrary code.
2492      */
2493     State threadState() {
2494         return jdk.internal.misc.VM.toThreadState(holder.threadStatus);
2495     }
2496 
2497     /**
2498      * Returns true if the thread has terminated.
2499      */
2500     boolean isTerminated() {
2501         return threadState() == State.TERMINATED;
2502     }
2503 
2504     /**
2505      * Interface for handlers invoked when a {@code Thread} abruptly
2506      * terminates due to an uncaught exception.
2507      * <p>When a thread is about to terminate due to an uncaught exception
2508      * the Java Virtual Machine will query the thread for its
2509      * {@code UncaughtExceptionHandler} using
2510      * {@link #getUncaughtExceptionHandler} and will invoke the handler's
2511      * {@code uncaughtException} method, passing the thread and the
2512      * exception as arguments.
2513      * If a thread has not had its {@code UncaughtExceptionHandler}
2514      * explicitly set, then its {@code ThreadGroup} object acts as its
2515      * {@code UncaughtExceptionHandler}. If the {@code ThreadGroup} object
2516      * has no
2517      * special requirements for dealing with the exception, it can forward
2518      * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
2519      * default uncaught exception handler}.
2520      *
2521      * @see #setDefaultUncaughtExceptionHandler
2522      * @see #setUncaughtExceptionHandler
2523      * @see ThreadGroup#uncaughtException
2524      * @since 1.5
2525      */
2526     @FunctionalInterface
2527     public interface UncaughtExceptionHandler {
2528         /**
2529          * Method invoked when the given thread terminates due to the
2530          * given uncaught exception.
2531          * <p>Any exception thrown by this method will be ignored by the
2532          * Java Virtual Machine.
2533          * @param t the thread
2534          * @param e the exception
2535          */
2536         void uncaughtException(Thread t, Throwable e);
2537     }
2538 
2539     // null unless explicitly set
2540     private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
2541 
2542     // null unless explicitly set
2543     private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
2544 
2545     /**
2546      * Set the default handler invoked when a thread abruptly terminates
2547      * due to an uncaught exception, and no other handler has been defined
2548      * for that thread.
2549      *
2550      * <p>Uncaught exception handling is controlled first by the thread, then
2551      * by the thread's {@link ThreadGroup} object and finally by the default
2552      * uncaught exception handler. If the thread does not have an explicit
2553      * uncaught exception handler set, and the thread's thread group
2554      * (including parent thread groups)  does not specialize its
2555      * {@code uncaughtException} method, then the default handler's
2556      * {@code uncaughtException} method will be invoked.
2557      * <p>By setting the default uncaught exception handler, an application
2558      * can change the way in which uncaught exceptions are handled (such as
2559      * logging to a specific device, or file) for those threads that would
2560      * already accept whatever &quot;default&quot; behavior the system
2561      * provided.
2562      *
2563      * <p>Note that the default uncaught exception handler should not usually
2564      * defer to the thread's {@code ThreadGroup} object, as that could cause
2565      * infinite recursion.
2566      *
2567      * @param ueh the object to use as the default uncaught exception handler.
2568      * If {@code null} then there is no default handler.
2569      *
2570      * @see #setUncaughtExceptionHandler
2571      * @see #getUncaughtExceptionHandler
2572      * @see ThreadGroup#uncaughtException
2573      * @since 1.5
2574      */
2575     public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2576         defaultUncaughtExceptionHandler = ueh;
2577     }
2578 
2579     /**
2580      * Returns the default handler invoked when a thread abruptly terminates
2581      * due to an uncaught exception. If the returned value is {@code null},
2582      * there is no default.
2583      * @since 1.5
2584      * @see #setDefaultUncaughtExceptionHandler
2585      * @return the default uncaught exception handler for all threads
2586      */
2587     public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
2588         return defaultUncaughtExceptionHandler;
2589     }
2590 
2591     /**
2592      * Returns the handler invoked when this thread abruptly terminates
2593      * due to an uncaught exception. If this thread has not had an
2594      * uncaught exception handler explicitly set then this thread's
2595      * {@code ThreadGroup} object is returned, unless this thread
2596      * has terminated, in which case {@code null} is returned.
2597      * @since 1.5
2598      * @return the uncaught exception handler for this thread
2599      */
2600     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2601         if (isTerminated()) {
2602             // uncaughtExceptionHandler may be set to null after thread terminates
2603             return null;
2604         } else {
2605             UncaughtExceptionHandler ueh = uncaughtExceptionHandler;
2606             return (ueh != null) ? ueh : getThreadGroup();
2607         }
2608     }
2609 
2610     /**
2611      * Set the handler invoked when this thread abruptly terminates
2612      * due to an uncaught exception.
2613      * <p>A thread can take full control of how it responds to uncaught
2614      * exceptions by having its uncaught exception handler explicitly set.
2615      * If no such handler is set then the thread's {@code ThreadGroup}
2616      * object acts as its handler.
2617      * @param ueh the object to use as this thread's uncaught exception
2618      * handler. If {@code null} then this thread has no explicit handler.
2619      * @see #setDefaultUncaughtExceptionHandler
2620      * @see ThreadGroup#uncaughtException
2621      * @since 1.5
2622      */
2623     public void setUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2624         uncaughtExceptionHandler(ueh);
2625     }
2626 
2627     void uncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2628         uncaughtExceptionHandler = ueh;
2629     }
2630 
2631     /**
2632      * Dispatch an uncaught exception to the handler. This method is
2633      * called when a thread terminates with an exception.
2634      */
2635     void dispatchUncaughtException(Throwable e) {
2636         getUncaughtExceptionHandler().uncaughtException(this, e);
2637     }
2638 
2639     /**
2640      * Holder class for constants.
2641      */
2642     private static class Constants {
2643         // Thread group for virtual threads.
2644         static final ThreadGroup VTHREAD_GROUP;
2645 
2646         static {
2647             ThreadGroup root = Thread.currentCarrierThread().getThreadGroup();
2648             for (ThreadGroup p; (p = root.getParent()) != null; ) {
2649                 root = p;
2650             }
2651             VTHREAD_GROUP = new ThreadGroup(root, "VirtualThreads", MAX_PRIORITY, false);
2652         }
2653     }
2654 
2655     /**
2656      * Returns the special ThreadGroup for virtual threads.
2657      */
2658     static ThreadGroup virtualThreadGroup() {
2659         return Constants.VTHREAD_GROUP;
2660     }
2661 
2662     // The following three initially uninitialized fields are exclusively
2663     // managed by class java.util.concurrent.ThreadLocalRandom. These
2664     // fields are used to build the high-performance PRNGs in the
2665     // concurrent code.
2666 
2667     /** The current seed for a ThreadLocalRandom */
2668     long threadLocalRandomSeed;
2669 
2670     /** Probe hash value; nonzero if threadLocalRandomSeed initialized */
2671     int threadLocalRandomProbe;
2672 
2673     /** Secondary seed isolated from public ThreadLocalRandom sequence */
2674     int threadLocalRandomSecondarySeed;
2675 
2676     /** The thread container that this thread is in */
2677     private @Stable ThreadContainer container;
2678     ThreadContainer threadContainer() {
2679         return container;
2680     }
2681     void setThreadContainer(ThreadContainer container) {
2682         // assert this.container == null;
2683         this.container = container;
2684     }
2685 
2686     /** The top of this stack of stackable scopes owned by this thread */
2687     private volatile StackableScope headStackableScopes;
2688     StackableScope headStackableScopes() {
2689         return headStackableScopes;
2690     }
2691     static void setHeadStackableScope(StackableScope scope) {
2692         currentThread().headStackableScopes = scope;
2693     }
2694 
2695     /* Some private helper methods */
2696     private native void setPriority0(int newPriority);
2697     private native void interrupt0();
2698     private static native void clearInterruptEvent();
2699     private native void setNativeName(String name);
2700 
2701     // The address of the next thread identifier, see ThreadIdentifiers.
2702     private static native long getNextThreadIdOffset();
2703 }