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