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