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      * Throws {@code UnsupportedOperationException}.
1642      *
1643      * @throws  UnsupportedOperationException always
1644      *
1645      * @deprecated This method was originally specified to "stop" a victim
1646      *       thread by causing the victim thread to throw a {@link ThreadDeath}.
1647      *       It was inherently unsafe. Stopping a thread caused it to unlock
1648      *       all of the monitors that it had locked (as a natural consequence
1649      *       of the {@code ThreadDeath} exception propagating up the stack). If
1650      *       any of the objects previously protected by these monitors were in
1651      *       an inconsistent state, the damaged objects became visible to
1652      *       other threads, potentially resulting in arbitrary behavior.
1653      *       Usages of {@code stop} should be replaced by code that simply
1654      *       modifies some variable to indicate that the target thread should
1655      *       stop running.  The target thread should check this variable
1656      *       regularly, and return from its run method in an orderly fashion
1657      *       if the variable indicates that it is to stop running.  If the
1658      *       target thread waits for long periods (on a condition variable,
1659      *       for example), the {@code interrupt} method should be used to
1660      *       interrupt the wait.
1661      *       For more information, see
1662      *       <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1663      *       is Thread.stop deprecated and the ability to stop a thread removed?</a>.
1664      */
1665     @Deprecated(since="1.2", forRemoval=true)
1666     public final void stop() {
1667         throw new UnsupportedOperationException();
1668     }
1669 
1670     /**
1671      * Interrupts this thread.
1672      *
1673      * <p> If this thread is blocked in an invocation of the {@link
1674      * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
1675      * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
1676      * class, or of the {@link #join()}, {@link #join(long)}, {@link
1677      * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}
1678      * methods of this class, then its interrupt status will be cleared and it
1679      * will receive an {@link InterruptedException}.
1680      *
1681      * <p> If this thread is blocked in an I/O operation upon an {@link
1682      * java.nio.channels.InterruptibleChannel InterruptibleChannel}
1683      * then the channel will be closed, the thread's interrupt
1684      * status will be set, and the thread will receive a {@link
1685      * java.nio.channels.ClosedByInterruptException}.
1686      *
1687      * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
1688      * then the thread's interrupt status will be set and it will return
1689      * immediately from the selection operation, possibly with a non-zero
1690      * value, just as if the selector's {@link
1691      * java.nio.channels.Selector#wakeup wakeup} method were invoked.
1692      *
1693      * <p> If none of the previous conditions hold then this thread's interrupt
1694      * status will be set. </p>
1695      *
1696      * <p> Interrupting a thread that is not alive need not have any effect.
1697      *
1698      * @implNote In the JDK Reference Implementation, interruption of a thread
1699      * that is not alive still records that the interrupt request was made and
1700      * will report it via {@link #interrupted()} and {@link #isInterrupted()}.
1701      */
1702     public void interrupt() {
1703         // Setting the interrupt status must be done before reading nioBlocker.
1704         interrupted = true;
1705         interrupt0();  // inform VM of interrupt
1706 
1707         // thread may be blocked in an I/O operation
1708         if (this != Thread.currentThread()) {
1709             Interruptible blocker;
1710             synchronized (interruptLock) {
1711                 blocker = nioBlocker;
1712                 if (blocker != null) {
1713                     blocker.interrupt(this);
1714                 }
1715             }
1716             if (blocker != null) {
1717                 blocker.postInterrupt();
1718             }
1719         }
1720     }
1721 
1722     /**
1723      * Tests whether the current thread has been interrupted.  The
1724      * <i>interrupted status</i> of the thread is cleared by this method.  In
1725      * other words, if this method were to be called twice in succession, the
1726      * second call would return false (unless the current thread were
1727      * interrupted again, after the first call had cleared its interrupted
1728      * status and before the second call had examined it).
1729      *
1730      * @return  {@code true} if the current thread has been interrupted;
1731      *          {@code false} otherwise.
1732      * @see #isInterrupted()
1733      */
1734     public static boolean interrupted() {
1735         return currentThread().getAndClearInterrupt();
1736     }
1737 
1738     /**
1739      * Tests whether this thread has been interrupted.  The <i>interrupted
1740      * status</i> of the thread is unaffected by this method.
1741      *
1742      * @return  {@code true} if this thread has been interrupted;
1743      *          {@code false} otherwise.
1744      * @see     #interrupted()
1745      */
1746     public boolean isInterrupted() {
1747         return interrupted;
1748     }
1749 
1750     final void setInterrupt() {
1751         // assert Thread.currentCarrierThread() == this;
1752         if (!interrupted) {
1753             interrupted = true;
1754             interrupt0();  // inform VM of interrupt
1755         }
1756     }
1757 
1758     final void clearInterrupt() {
1759         // assert Thread.currentCarrierThread() == this;
1760         if (interrupted) {
1761             interrupted = false;
1762             clearInterruptEvent();
1763         }
1764     }
1765 
1766     boolean getAndClearInterrupt() {
1767         boolean oldValue = interrupted;
1768         // We may have been interrupted the moment after we read the field,
1769         // so only clear the field if we saw that it was set and will return
1770         // true; otherwise we could lose an interrupt.
1771         if (oldValue) {
1772             interrupted = false;
1773             clearInterruptEvent();
1774         }
1775         return oldValue;
1776     }
1777 
1778     /**
1779      * Tests if this thread is alive. A thread is alive if it has
1780      * been started and has not yet terminated.
1781      *
1782      * @return  {@code true} if this thread is alive;
1783      *          {@code false} otherwise.
1784      */
1785     public final boolean isAlive() {
1786         return alive();
1787     }
1788 
1789     /**
1790      * Returns true if this thread is alive.
1791      * This method is non-final so it can be overridden.
1792      */
1793     boolean alive() {
1794         return eetop != 0;
1795     }
1796 
1797     /**
1798      * Changes the priority of this thread.
1799      *
1800      * For platform threads, the priority is set to the smaller of the specified
1801      * {@code newPriority} and the maximum permitted priority of the thread's
1802      * {@linkplain ThreadGroup thread group}.
1803      *
1804      * The priority of a virtual thread is always {@link Thread#NORM_PRIORITY}
1805      * and {@code newPriority} is ignored.
1806      *
1807      * @param newPriority the new thread priority
1808      * @throws  IllegalArgumentException if the priority is not in the
1809      *          range {@code MIN_PRIORITY} to {@code MAX_PRIORITY}.
1810      * @see #setPriority(int)
1811      * @see ThreadGroup#getMaxPriority()
1812      */
1813     public final void setPriority(int newPriority) {
1814         if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
1815             throw new IllegalArgumentException();
1816         }
1817         if (!isVirtual()) {
1818             priority(newPriority);
1819         }
1820     }
1821 
1822     void priority(int newPriority) {
1823         ThreadGroup g = holder.group;
1824         if (g != null) {
1825             int maxPriority = g.getMaxPriority();
1826             if (newPriority > maxPriority) {
1827                 newPriority = maxPriority;
1828             }
1829             setPriority0(holder.priority = newPriority);
1830         }
1831     }
1832 
1833     /**
1834      * Returns this thread's priority.
1835      *
1836      * <p> The priority of a virtual thread is always {@link Thread#NORM_PRIORITY}.
1837      *
1838      * @return  this thread's priority.
1839      * @see     #setPriority
1840      */
1841     public final int getPriority() {
1842         if (isVirtual()) {
1843             return Thread.NORM_PRIORITY;
1844         } else {
1845             return holder.priority;
1846         }
1847     }
1848 
1849     /**
1850      * Changes the name of this thread to be equal to the argument {@code name}.
1851      *
1852      * @implNote In the JDK Reference Implementation, if this thread is the
1853      * current thread, and it's a platform thread that was not attached to the
1854      * VM with the Java Native Interface
1855      * <a href="{@docRoot}/../specs/jni/invocation.html#attachcurrentthread">
1856      * AttachCurrentThread</a> function, then this method will set the operating
1857      * system thread name. This may be useful for debugging and troubleshooting
1858      * purposes.
1859      *
1860      * @param      name   the new name for this thread.
1861      *
1862      * @spec jni/index.html Java Native Interface Specification
1863      * @see        #getName
1864      */
1865     public final synchronized void setName(String name) {
1866         if (name == null) {
1867             throw new NullPointerException("name cannot be null");
1868         }
1869         this.name = name;
1870         if (!isVirtual() && Thread.currentThread() == this) {
1871             setNativeName(name);
1872         }
1873     }
1874 
1875     /**
1876      * Returns this thread's name.
1877      *
1878      * @return  this thread's name.
1879      * @see     #setName(String)
1880      */
1881     public final String getName() {
1882         return name;
1883     }
1884 
1885     /**
1886      * Returns the thread's thread group or {@code null} if the thread has
1887      * terminated.
1888      *
1889      * <p> The thread group returned for a virtual thread is the special
1890      * <a href="ThreadGroup.html#virtualthreadgroup"><em>ThreadGroup for
1891      * virtual threads</em></a>.
1892      *
1893      * @return  this thread's thread group or {@code null}
1894      */
1895     public final ThreadGroup getThreadGroup() {
1896         if (isTerminated()) {
1897             return null;
1898         } else {
1899             return isVirtual() ? virtualThreadGroup() : holder.group;
1900         }
1901     }
1902 
1903     /**
1904      * Returns an estimate of the number of {@linkplain #isAlive() live}
1905      * platform threads in the current thread's thread group and its subgroups.
1906      * Virtual threads are not included in the estimate.
1907      *
1908      * <p> The value returned is only an estimate because the number of
1909      * threads may change dynamically while this method traverses internal
1910      * data structures, and might be affected by the presence of certain
1911      * system threads. This method is intended primarily for debugging
1912      * and monitoring purposes.
1913      *
1914      * @return  an estimate of the number of live platform threads in the
1915      *          current thread's thread group and in any other thread group
1916      *          that has the current thread's thread group as an ancestor
1917      */
1918     public static int activeCount() {
1919         return currentThread().getThreadGroup().activeCount();
1920     }
1921 
1922     /**
1923      * Copies into the specified array every {@linkplain #isAlive() live}
1924      * platform thread in the current thread's thread group and its subgroups.
1925      * This method simply invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
1926      * method of the current thread's thread group. Virtual threads are
1927      * not enumerated by this method.
1928      *
1929      * <p> An application might use the {@linkplain #activeCount activeCount}
1930      * method to get an estimate of how big the array should be, however
1931      * <i>if the array is too short to hold all the threads, the extra threads
1932      * are silently ignored.</i>  If it is critical to obtain every live
1933      * thread in the current thread's thread group and its subgroups, the
1934      * invoker should verify that the returned int value is strictly less
1935      * than the length of {@code tarray}.
1936      *
1937      * <p> Due to the inherent race condition in this method, it is recommended
1938      * that the method only be used for debugging and monitoring purposes.
1939      *
1940      * @param  tarray
1941      *         an array into which to put the list of threads
1942      *
1943      * @return  the number of threads put into the array
1944      */
1945     public static int enumerate(Thread[] tarray) {
1946         return currentThread().getThreadGroup().enumerate(tarray);
1947     }
1948 
1949     /**
1950      * Waits at most {@code millis} milliseconds for this thread to terminate.
1951      * A timeout of {@code 0} means to wait forever.
1952      * This method returns immediately, without waiting, if the thread has not
1953      * been {@link #start() started}.
1954      *
1955      * @implNote
1956      * For platform threads, the implementation uses a loop of {@code this.wait}
1957      * calls conditioned on {@code this.isAlive}. As a thread terminates the
1958      * {@code this.notifyAll} method is invoked. It is recommended that
1959      * applications not use {@code wait}, {@code notify}, or
1960      * {@code notifyAll} on {@code Thread} instances.
1961      *
1962      * @param  millis
1963      *         the time to wait in milliseconds
1964      *
1965      * @throws  IllegalArgumentException
1966      *          if the value of {@code millis} is negative
1967      *
1968      * @throws  InterruptedException
1969      *          if any thread has interrupted the current thread. The
1970      *          <i>interrupted status</i> of the current thread is
1971      *          cleared when this exception is thrown.
1972      */
1973     public final void join(long millis) throws InterruptedException {
1974         if (millis < 0)
1975             throw new IllegalArgumentException("timeout value is negative");
1976 
1977         if (this instanceof VirtualThread vthread) {
1978             if (isAlive()) {
1979                 long nanos = MILLISECONDS.toNanos(millis);
1980                 vthread.joinNanos(nanos);
1981             }
1982             return;
1983         }
1984 
1985         synchronized (this) {
1986             if (millis > 0) {
1987                 if (isAlive()) {
1988                     final long startTime = System.nanoTime();
1989                     long delay = millis;
1990                     do {
1991                         wait(delay);
1992                     } while (isAlive() && (delay = millis -
1993                              NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
1994                 }
1995             } else {
1996                 while (isAlive()) {
1997                     wait(0);
1998                 }
1999             }
2000         }
2001     }
2002 
2003     /**
2004      * Waits at most {@code millis} milliseconds plus
2005      * {@code nanos} nanoseconds for this thread to terminate.
2006      * If both arguments are {@code 0}, it means to wait forever.
2007      * This method returns immediately, without waiting, if the thread has not
2008      * been {@link #start() started}.
2009      *
2010      * @implNote
2011      * For platform threads, the implementation uses a loop of {@code this.wait}
2012      * calls conditioned on {@code this.isAlive}. As a thread terminates the
2013      * {@code this.notifyAll} method is invoked. It is recommended that
2014      * applications not use {@code wait}, {@code notify}, or
2015      * {@code notifyAll} on {@code Thread} instances.
2016      *
2017      * @param  millis
2018      *         the time to wait in milliseconds
2019      *
2020      * @param  nanos
2021      *         {@code 0-999999} additional nanoseconds to wait
2022      *
2023      * @throws  IllegalArgumentException
2024      *          if the value of {@code millis} is negative, or the value
2025      *          of {@code nanos} is not in the range {@code 0-999999}
2026      *
2027      * @throws  InterruptedException
2028      *          if any thread has interrupted the current thread. The
2029      *          <i>interrupted status</i> of the current thread is
2030      *          cleared when this exception is thrown.
2031      */
2032     public final void join(long millis, int nanos) throws InterruptedException {
2033         if (millis < 0) {
2034             throw new IllegalArgumentException("timeout value is negative");
2035         }
2036 
2037         if (nanos < 0 || nanos > 999999) {
2038             throw new IllegalArgumentException("nanosecond timeout value out of range");
2039         }
2040 
2041         if (this instanceof VirtualThread vthread) {
2042             if (isAlive()) {
2043                 // convert arguments to a total in nanoseconds
2044                 long totalNanos = MILLISECONDS.toNanos(millis);
2045                 totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos);
2046                 vthread.joinNanos(totalNanos);
2047             }
2048             return;
2049         }
2050 
2051         if (nanos > 0 && millis < Long.MAX_VALUE) {
2052             millis++;
2053         }
2054         join(millis);
2055     }
2056 
2057     /**
2058      * Waits for this thread to terminate.
2059      *
2060      * <p> An invocation of this method behaves in exactly the same
2061      * way as the invocation
2062      *
2063      * <blockquote>
2064      * {@linkplain #join(long) join}{@code (0)}
2065      * </blockquote>
2066      *
2067      * @throws  InterruptedException
2068      *          if any thread has interrupted the current thread. The
2069      *          <i>interrupted status</i> of the current thread is
2070      *          cleared when this exception is thrown.
2071      */
2072     public final void join() throws InterruptedException {
2073         join(0);
2074     }
2075 
2076     /**
2077      * Waits for this thread to terminate for up to the given waiting duration.
2078      *
2079      * <p> This method does not wait if the duration to wait is less than or
2080      * equal to zero. In this case, the method just tests if the thread has
2081      * terminated.
2082      *
2083      * @param   duration
2084      *          the maximum duration to wait
2085      *
2086      * @return  {@code true} if the thread has terminated, {@code false} if the
2087      *          thread has not terminated
2088      *
2089      * @throws  InterruptedException
2090      *          if the current thread is interrupted while waiting.
2091      *          The <i>interrupted status</i> of the current thread is cleared
2092      *          when this exception is thrown.
2093      *
2094      * @throws  IllegalThreadStateException
2095      *          if this thread has not been started.
2096      *
2097      * @since 19
2098      */
2099     public final boolean join(Duration duration) throws InterruptedException {
2100         long nanos = NANOSECONDS.convert(duration); // MAX_VALUE if > 292 years
2101 
2102         Thread.State state = threadState();
2103         if (state == State.NEW)
2104             throw new IllegalThreadStateException("Thread not started");
2105         if (state == State.TERMINATED)
2106             return true;
2107         if (nanos <= 0)
2108             return false;
2109 
2110         if (this instanceof VirtualThread vthread) {
2111             return vthread.joinNanos(nanos);
2112         }
2113 
2114         // convert to milliseconds
2115         long millis = MILLISECONDS.convert(nanos, NANOSECONDS);
2116         if (nanos > NANOSECONDS.convert(millis, MILLISECONDS)) {
2117             millis += 1L;
2118         }
2119         join(millis);
2120         return isTerminated();
2121     }
2122 
2123     /**
2124      * Prints a stack trace of the current thread to the standard error stream.
2125      * This method is useful for debugging.
2126      */
2127     public static void dumpStack() {
2128         new Exception("Stack trace").printStackTrace();
2129     }
2130 
2131     /**
2132      * Marks this thread as either a <i>daemon</i> or <i>non-daemon</i> thread.
2133      * The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all
2134      * started non-daemon threads have terminated.
2135      *
2136      * <p> The daemon status of a virtual thread is always {@code true} and cannot be
2137      * changed by this method to {@code false}.
2138      *
2139      * <p> This method must be invoked before the thread is started. The behavior
2140      * of this method when the thread has terminated is not specified.
2141      *
2142      * @param  on
2143      *         if {@code true}, marks this thread as a daemon thread
2144      *
2145      * @throws  IllegalArgumentException
2146      *          if this is a virtual thread and {@code on} is false
2147      * @throws  IllegalThreadStateException
2148      *          if this thread is {@linkplain #isAlive alive}
2149      */
2150     public final void setDaemon(boolean on) {
2151         if (isVirtual() && !on)
2152             throw new IllegalArgumentException("'false' not legal for virtual threads");
2153         if (isAlive())
2154             throw new IllegalThreadStateException();
2155         if (!isVirtual())
2156             daemon(on);
2157     }
2158 
2159     void daemon(boolean on) {
2160         holder.daemon = on;
2161     }
2162 
2163     /**
2164      * Tests if this thread is a daemon thread.
2165      * The daemon status of a virtual thread is always {@code true}.
2166      *
2167      * @return  {@code true} if this thread is a daemon thread;
2168      *          {@code false} otherwise.
2169      * @see     #setDaemon(boolean)
2170      */
2171     public final boolean isDaemon() {
2172         if (isVirtual()) {
2173             return true;
2174         } else {
2175             return holder.daemon;
2176         }
2177     }
2178 
2179     /**
2180      * Does nothing.
2181      *
2182      * @deprecated This method originally determined if the currently running
2183      * thread had permission to modify this thread. This method was only useful
2184      * in conjunction with {@linkplain SecurityManager the Security Manager},
2185      * which is no longer supported. There is no replacement for the Security
2186      * Manager or this method.
2187      */
2188     @Deprecated(since="17", forRemoval=true)
2189     public final void checkAccess() { }
2190 
2191     /**
2192      * Returns a string representation of this thread. The string representation
2193      * will usually include the thread's {@linkplain #threadId() identifier} and
2194      * name. The default implementation for platform threads includes the thread's
2195      * identifier, name, priority, and the name of the thread group.
2196      *
2197      * @return  a string representation of this thread.
2198      */
2199     public String toString() {
2200         StringBuilder sb = new StringBuilder("Thread[#");
2201         sb.append(threadId());
2202         sb.append(",");
2203         sb.append(getName());
2204         sb.append(",");
2205         sb.append(getPriority());
2206         sb.append(",");
2207         ThreadGroup group = getThreadGroup();
2208         if (group != null)
2209             sb.append(group.getName());
2210         sb.append("]");
2211         return sb.toString();
2212     }
2213 
2214     /**
2215      * Returns the context {@code ClassLoader} for this thread.
2216      * The context {@code ClassLoader} may be set by the creator of the thread
2217      * for use by code running in this thread when loading classes and resources.
2218      * If not {@linkplain #setContextClassLoader set}, the default is to inherit
2219      * the context class loader from the parent thread.
2220      *
2221      * <p> The context {@code ClassLoader} of the primordial thread is typically
2222      * set to the class loader used to load the application.
2223      *
2224      * @return  the context {@code ClassLoader} for this thread, or {@code null}
2225      *          indicating the system class loader (or, failing that, the
2226      *          bootstrap class loader)
2227      *
2228      * @since 1.2
2229      */
2230     public ClassLoader getContextClassLoader() {
2231         return contextClassLoader;
2232     }
2233 
2234     /**
2235      * Sets the context {@code ClassLoader} for this thread.
2236      *
2237      * <p> The context {@code ClassLoader} may be set by the creator of the thread
2238      * for use by code running in this thread when loading classes and resources.
2239      *
2240      * @param  cl
2241      *         the context ClassLoader for this Thread, or null  indicating the
2242      *         system class loader (or, failing that, the bootstrap class loader)
2243      *
2244      * @since 1.2
2245      */
2246     public void setContextClassLoader(ClassLoader cl) {
2247         contextClassLoader = cl;
2248     }
2249 
2250     /**
2251      * Returns {@code true} if and only if the current thread holds the
2252      * monitor lock on the specified object.
2253      *
2254      * <p>This method is designed to allow a program to assert that
2255      * the current thread already holds a specified lock:
2256      * <pre>
2257      *     assert Thread.holdsLock(obj);
2258      * </pre>
2259      *
2260      * @param  obj the object on which to test lock ownership
2261      * @return {@code true} if the current thread holds the monitor lock on
2262      *         the specified object.
2263      * @since 1.4
2264      */
2265     public static native boolean holdsLock(Object obj);
2266 
2267     private static final StackTraceElement[] EMPTY_STACK_TRACE
2268         = new StackTraceElement[0];
2269 
2270     /**
2271      * Returns an array of stack trace elements representing the stack dump
2272      * of this thread.  This method will return a zero-length array if
2273      * this thread has not started, has started but has not yet been
2274      * scheduled to run by the system, or has terminated.
2275      * If the returned array is of non-zero length then the first element of
2276      * the array represents the top of the stack, which is the most recent
2277      * method invocation in the sequence.  The last element of the array
2278      * represents the bottom of the stack, which is the least recent method
2279      * invocation in the sequence.
2280      *
2281      * <p>Some virtual machines may, under some circumstances, omit one
2282      * or more stack frames from the stack trace.  In the extreme case,
2283      * a virtual machine that has no stack trace information concerning
2284      * this thread is permitted to return a zero-length array from this
2285      * method.
2286      *
2287      * @return an array of {@code StackTraceElement},
2288      * each represents one stack frame.
2289      *
2290      * @see Throwable#getStackTrace
2291      * @since 1.5
2292      */
2293     public StackTraceElement[] getStackTrace() {
2294         if (this != Thread.currentThread()) {
2295             // optimization so we do not call into the vm for threads that
2296             // have not yet started or have terminated
2297             if (!isAlive()) {
2298                 return EMPTY_STACK_TRACE;
2299             }
2300             StackTraceElement[] stackTrace = asyncGetStackTrace();
2301             return (stackTrace != null) ? stackTrace : EMPTY_STACK_TRACE;
2302         } else {
2303             return (new Exception()).getStackTrace();
2304         }
2305     }
2306 
2307     /**
2308      * Returns an array of stack trace elements representing the stack dump of
2309      * this thread. Returns null if the stack trace cannot be obtained. In
2310      * the default implementation, null is returned if the thread is a virtual
2311      * thread that is not mounted or the thread is a platform thread that has
2312      * terminated.
2313      */
2314     StackTraceElement[] asyncGetStackTrace() {
2315         Object stackTrace = getStackTrace0();
2316         if (stackTrace == null) {
2317             return null;
2318         }
2319         StackTraceElement[] stes = (StackTraceElement[]) stackTrace;
2320         if (stes.length == 0) {
2321             return null;
2322         } else {
2323             return StackTraceElement.of(stes);
2324         }
2325     }
2326 
2327     private native Object getStackTrace0();
2328 
2329     /**
2330      * Returns a map of stack traces for all live platform threads. The map
2331      * does not include virtual threads.
2332      * The map keys are threads and each map value is an array of
2333      * {@code StackTraceElement} that represents the stack dump
2334      * of the corresponding {@code Thread}.
2335      * The returned stack traces are in the format specified for
2336      * the {@link #getStackTrace getStackTrace} method.
2337      *
2338      * <p>The threads may be executing while this method is called.
2339      * The stack trace of each thread only represents a snapshot and
2340      * each stack trace may be obtained at different time.  A zero-length
2341      * array will be returned in the map value if the virtual machine has
2342      * no stack trace information about a thread.
2343      *
2344      * @return a {@code Map} from {@code Thread} to an array of
2345      * {@code StackTraceElement} that represents the stack trace of
2346      * the corresponding thread.
2347      *
2348      * @see #getStackTrace
2349      * @see Throwable#getStackTrace
2350      *
2351      * @since 1.5
2352      */
2353     public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
2354         // Get a snapshot of the list of all threads
2355         Thread[] threads = getThreads();
2356         StackTraceElement[][] traces = dumpThreads(threads);
2357         Map<Thread, StackTraceElement[]> m = HashMap.newHashMap(threads.length);
2358         for (int i = 0; i < threads.length; i++) {
2359             StackTraceElement[] stackTrace = traces[i];
2360             if (stackTrace != null) {
2361                 m.put(threads[i], stackTrace);
2362             }
2363             // else terminated so we don't put it in the map
2364         }
2365         return m;
2366     }
2367 
2368     /**
2369      * Return an array of all live threads.
2370      */
2371     static Thread[] getAllThreads() {
2372         return getThreads();
2373     }
2374 
2375     private static native StackTraceElement[][] dumpThreads(Thread[] threads);
2376     private static native Thread[] getThreads();
2377 
2378     /**
2379      * Returns the identifier of this Thread.  The thread ID is a positive
2380      * {@code long} number generated when this thread was created.
2381      * The thread ID is unique and remains unchanged during its lifetime.
2382      *
2383      * @return this thread's ID
2384      *
2385      * @deprecated This method is not final and may be overridden to return a
2386      * value that is not the thread ID. Use {@link #threadId()} instead.
2387      *
2388      * @since 1.5
2389      */
2390     @Deprecated(since="19")
2391     public long getId() {
2392         return threadId();
2393     }
2394 
2395     /**
2396      * Returns the identifier of this Thread.  The thread ID is a positive
2397      * {@code long} number generated when this thread was created.
2398      * The thread ID is unique and remains unchanged during its lifetime.
2399      *
2400      * @return this thread's ID
2401      * @since 19
2402      */
2403     public final long threadId() {
2404         return tid;
2405     }
2406 
2407     /**
2408      * A thread state.  A thread can be in one of the following states:
2409      * <ul>
2410      * <li>{@link #NEW}<br>
2411      *     A thread that has not yet started is in this state.
2412      *     </li>
2413      * <li>{@link #RUNNABLE}<br>
2414      *     A thread executing in the Java virtual machine is in this state.
2415      *     </li>
2416      * <li>{@link #BLOCKED}<br>
2417      *     A thread that is blocked waiting for a monitor lock
2418      *     is in this state.
2419      *     </li>
2420      * <li>{@link #WAITING}<br>
2421      *     A thread that is waiting indefinitely for another thread to
2422      *     perform a particular action is in this state.
2423      *     </li>
2424      * <li>{@link #TIMED_WAITING}<br>
2425      *     A thread that is waiting for another thread to perform an action
2426      *     for up to a specified waiting time is in this state.
2427      *     </li>
2428      * <li>{@link #TERMINATED}<br>
2429      *     A thread that has exited is in this state.
2430      *     </li>
2431      * </ul>
2432      *
2433      * <p>
2434      * A thread can be in only one state at a given point in time.
2435      * These states are virtual machine states which do not reflect
2436      * any operating system thread states.
2437      *
2438      * @since   1.5
2439      * @see #getState
2440      */
2441     public enum State {
2442         /**
2443          * Thread state for a thread which has not yet started.
2444          */
2445         NEW,
2446 
2447         /**
2448          * Thread state for a runnable thread.  A thread in the runnable
2449          * state is executing in the Java virtual machine but it may
2450          * be waiting for other resources from the operating system
2451          * such as processor.
2452          */
2453         RUNNABLE,
2454 
2455         /**
2456          * Thread state for a thread blocked waiting for a monitor lock.
2457          * A thread in the blocked state is waiting for a monitor lock
2458          * to enter a synchronized block/method or
2459          * reenter a synchronized block/method after calling
2460          * {@link Object#wait() Object.wait}.
2461          */
2462         BLOCKED,
2463 
2464         /**
2465          * Thread state for a waiting thread.
2466          * A thread is in the waiting state due to calling one of the
2467          * following methods:
2468          * <ul>
2469          *   <li>{@link Object#wait() Object.wait} with no timeout</li>
2470          *   <li>{@link #join() Thread.join} with no timeout</li>
2471          *   <li>{@link LockSupport#park() LockSupport.park}</li>
2472          * </ul>
2473          *
2474          * <p>A thread in the waiting state is waiting for another thread to
2475          * perform a particular action.
2476          *
2477          * For example, a thread that has called {@code Object.wait()}
2478          * on an object is waiting for another thread to call
2479          * {@code Object.notify()} or {@code Object.notifyAll()} on
2480          * that object. A thread that has called {@code Thread.join()}
2481          * is waiting for a specified thread to terminate.
2482          */
2483         WAITING,
2484 
2485         /**
2486          * Thread state for a waiting thread with a specified waiting time.
2487          * A thread is in the timed waiting state due to calling one of
2488          * the following methods with a specified positive waiting time:
2489          * <ul>
2490          *   <li>{@link #sleep Thread.sleep}</li>
2491          *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
2492          *   <li>{@link #join(long) Thread.join} with timeout</li>
2493          *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
2494          *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
2495          * </ul>
2496          */
2497         TIMED_WAITING,
2498 
2499         /**
2500          * Thread state for a terminated thread.
2501          * The thread has completed execution.
2502          */
2503         TERMINATED;
2504     }
2505 
2506     /**
2507      * Returns the state of this thread.
2508      * This method is designed for use in monitoring of the system state,
2509      * not for synchronization control.
2510      *
2511      * @return this thread's state.
2512      * @since 1.5
2513      */
2514     public State getState() {
2515         return threadState();
2516     }
2517 
2518     /**
2519      * Returns the state of this thread.
2520      * This method can be used instead of getState as getState is not final and
2521      * so can be overridden to run arbitrary code.
2522      */
2523     State threadState() {
2524         return jdk.internal.misc.VM.toThreadState(holder.threadStatus);
2525     }
2526 
2527     /**
2528      * Returns true if the thread has terminated.
2529      */
2530     boolean isTerminated() {
2531         return threadState() == State.TERMINATED;
2532     }
2533 
2534     /**
2535      * Interface for handlers invoked when a {@code Thread} abruptly
2536      * terminates due to an uncaught exception.
2537      * <p>When a thread is about to terminate due to an uncaught exception
2538      * the Java Virtual Machine will query the thread for its
2539      * {@code UncaughtExceptionHandler} using
2540      * {@link #getUncaughtExceptionHandler} and will invoke the handler's
2541      * {@code uncaughtException} method, passing the thread and the
2542      * exception as arguments.
2543      * If a thread has not had its {@code UncaughtExceptionHandler}
2544      * explicitly set, then its {@code ThreadGroup} object acts as its
2545      * {@code UncaughtExceptionHandler}. If the {@code ThreadGroup} object
2546      * has no
2547      * special requirements for dealing with the exception, it can forward
2548      * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
2549      * default uncaught exception handler}.
2550      *
2551      * @see #setDefaultUncaughtExceptionHandler
2552      * @see #setUncaughtExceptionHandler
2553      * @see ThreadGroup#uncaughtException
2554      * @since 1.5
2555      */
2556     @FunctionalInterface
2557     public interface UncaughtExceptionHandler {
2558         /**
2559          * Method invoked when the given thread terminates due to the
2560          * given uncaught exception.
2561          * <p>Any exception thrown by this method will be ignored by the
2562          * Java Virtual Machine.
2563          * @param t the thread
2564          * @param e the exception
2565          */
2566         void uncaughtException(Thread t, Throwable e);
2567     }
2568 
2569     // null unless explicitly set
2570     private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
2571 
2572     // null unless explicitly set
2573     private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
2574 
2575     /**
2576      * Set the default handler invoked when a thread abruptly terminates
2577      * due to an uncaught exception, and no other handler has been defined
2578      * for that thread.
2579      *
2580      * <p>Uncaught exception handling is controlled first by the thread, then
2581      * by the thread's {@link ThreadGroup} object and finally by the default
2582      * uncaught exception handler. If the thread does not have an explicit
2583      * uncaught exception handler set, and the thread's thread group
2584      * (including parent thread groups)  does not specialize its
2585      * {@code uncaughtException} method, then the default handler's
2586      * {@code uncaughtException} method will be invoked.
2587      * <p>By setting the default uncaught exception handler, an application
2588      * can change the way in which uncaught exceptions are handled (such as
2589      * logging to a specific device, or file) for those threads that would
2590      * already accept whatever &quot;default&quot; behavior the system
2591      * provided.
2592      *
2593      * <p>Note that the default uncaught exception handler should not usually
2594      * defer to the thread's {@code ThreadGroup} object, as that could cause
2595      * infinite recursion.
2596      *
2597      * @param ueh the object to use as the default uncaught exception handler.
2598      * If {@code null} then there is no default handler.
2599      *
2600      * @see #setUncaughtExceptionHandler
2601      * @see #getUncaughtExceptionHandler
2602      * @see ThreadGroup#uncaughtException
2603      * @since 1.5
2604      */
2605     public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2606         defaultUncaughtExceptionHandler = ueh;
2607     }
2608 
2609     /**
2610      * Returns the default handler invoked when a thread abruptly terminates
2611      * due to an uncaught exception. If the returned value is {@code null},
2612      * there is no default.
2613      * @since 1.5
2614      * @see #setDefaultUncaughtExceptionHandler
2615      * @return the default uncaught exception handler for all threads
2616      */
2617     public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
2618         return defaultUncaughtExceptionHandler;
2619     }
2620 
2621     /**
2622      * Returns the handler invoked when this thread abruptly terminates
2623      * due to an uncaught exception. If this thread has not had an
2624      * uncaught exception handler explicitly set then this thread's
2625      * {@code ThreadGroup} object is returned, unless this thread
2626      * has terminated, in which case {@code null} is returned.
2627      * @since 1.5
2628      * @return the uncaught exception handler for this thread
2629      */
2630     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2631         if (isTerminated()) {
2632             // uncaughtExceptionHandler may be set to null after thread terminates
2633             return null;
2634         } else {
2635             UncaughtExceptionHandler ueh = uncaughtExceptionHandler;
2636             return (ueh != null) ? ueh : getThreadGroup();
2637         }
2638     }
2639 
2640     /**
2641      * Set the handler invoked when this thread abruptly terminates
2642      * due to an uncaught exception.
2643      * <p>A thread can take full control of how it responds to uncaught
2644      * exceptions by having its uncaught exception handler explicitly set.
2645      * If no such handler is set then the thread's {@code ThreadGroup}
2646      * object acts as its handler.
2647      * @param ueh the object to use as this thread's uncaught exception
2648      * handler. If {@code null} then this thread has no explicit handler.
2649      * @see #setDefaultUncaughtExceptionHandler
2650      * @see ThreadGroup#uncaughtException
2651      * @since 1.5
2652      */
2653     public void setUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2654         uncaughtExceptionHandler(ueh);
2655     }
2656 
2657     void uncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2658         uncaughtExceptionHandler = ueh;
2659     }
2660 
2661     /**
2662      * Dispatch an uncaught exception to the handler. This method is
2663      * called when a thread terminates with an exception.
2664      */
2665     void dispatchUncaughtException(Throwable e) {
2666         getUncaughtExceptionHandler().uncaughtException(this, e);
2667     }
2668 
2669     /**
2670      * Holder class for constants.
2671      */
2672     private static class Constants {
2673         // Thread group for virtual threads.
2674         static final ThreadGroup VTHREAD_GROUP;
2675 
2676         static {
2677             ThreadGroup root = Thread.currentCarrierThread().getThreadGroup();
2678             for (ThreadGroup p; (p = root.getParent()) != null; ) {
2679                 root = p;
2680             }
2681             VTHREAD_GROUP = new ThreadGroup(root, "VirtualThreads", MAX_PRIORITY, false);
2682         }
2683     }
2684 
2685     /**
2686      * Returns the special ThreadGroup for virtual threads.
2687      */
2688     static ThreadGroup virtualThreadGroup() {
2689         return Constants.VTHREAD_GROUP;
2690     }
2691 
2692     // The following three initially uninitialized fields are exclusively
2693     // managed by class java.util.concurrent.ThreadLocalRandom. These
2694     // fields are used to build the high-performance PRNGs in the
2695     // concurrent code.
2696 
2697     /** The current seed for a ThreadLocalRandom */
2698     long threadLocalRandomSeed;
2699 
2700     /** Probe hash value; nonzero if threadLocalRandomSeed initialized */
2701     int threadLocalRandomProbe;
2702 
2703     /** Secondary seed isolated from public ThreadLocalRandom sequence */
2704     int threadLocalRandomSecondarySeed;
2705 
2706     /** The thread container that this thread is in */
2707     private @Stable ThreadContainer container;
2708     ThreadContainer threadContainer() {
2709         return container;
2710     }
2711     void setThreadContainer(ThreadContainer container) {
2712         // assert this.container == null;
2713         this.container = container;
2714     }
2715 
2716     /** The top of this stack of stackable scopes owned by this thread */
2717     private volatile StackableScope headStackableScopes;
2718     StackableScope headStackableScopes() {
2719         return headStackableScopes;
2720     }
2721     static void setHeadStackableScope(StackableScope scope) {
2722         currentThread().headStackableScopes = scope;
2723     }
2724 
2725     /* Some private helper methods */
2726     private native void setPriority0(int newPriority);
2727     private native void interrupt0();
2728     private static native void clearInterruptEvent();
2729     private native void setNativeName(String name);
2730 
2731     // The address of the next thread identifier, see ThreadIdentifiers.
2732     private static native long getNextThreadIdOffset();
2733 }