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