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